diff --git a/tests/unittest/BUILD.gn b/tests/unittest/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..ee9e875f85b81c6f98c7e6b45b73dea6a4593621 --- /dev/null +++ b/tests/unittest/BUILD.gn @@ -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. + +import("//build/ohos.gni") + +config("utest_config") { + visibility = [ ":*" ] + + cflags = [ + "-fprofile-arcs", + "-ftest-coverage", + "-Wno-implicit-fallthrough", + "-Wno-unused-function" + ] + cflags_cc =[ "-Wno-implicit-fallthrough" ] + + ldflags = [ + "--coverage", + ] +} + +ohos_executable("updaterserver_ut") { + sources = [ + "update_server_ut_entry.cpp", + "update_client/client_stub.cpp", + "update_client/client_unittest.cpp", + "update_engine/server_unittest.cpp", + ] + + sources += [ + "//base/update/updateservice/client/update_client.cpp", + "//base/update/updateservice/client/update_session.cpp", + "//base/update/updateservice/client/update_module.cpp", + "//base/update/updateservice/interfaces/innerkits/engine/update_service_proxy.cpp", + "//base/update/updateservice/interfaces/innerkits/engine/update_service_kits_impl.cpp", + "//base/update/updateservice/engine/src/update_service.cpp", + "//base/update/updateservice/engine/src/update_service_stub.cpp", + "//base/update/updateservice/engine/src/update_helper.cpp", + "//base/update/updateservice/engine/src/progress_thread.cpp", + "//base/update/updateservice/callback/src/update_callback_proxy.cpp", + "//base/update/updateservice/callback/src/update_callback_stub.cpp", + "//base/update/updateservice/callback/src/update_callback.cpp", + "//base/update/updater/interfaces/kits/packages/package.cpp" + ] + include_dirs = [ + "//base/update/updater/interfaces/kits/include/", + "//base/update/updater/interfaces/kits/include/package", + "//base/update/updateservice", + "//base/update/updateservice/interfaces/innerkits/include", + "//base/update/updateservice/client", + "//base/update/updateservice/engine/include", + "//base/update/updateservice/callback/include", + "//base/update/updater/utils/include/", + "//base/update/updater/services/include/", + "//base/update/updater/services/include/log", + "//base/update/updater/services/include/package", + "//base/update/updater/tests/unittest", + "//third_party/bounds_checking_function/include", + "//third_party/node/src", + "//foundation/ace/napi/interfaces/kits", + "//third_party/cJSON", + "//third_party/libxml2/include", + "//third_party/curl/include", + "//third_party/openssl/include", + "//third_party/bounds_checking_function/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/distributedschedule/safwk/services/safwk/include", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + ] + + deps = [ + "//third_party/googletest:gtest", + "//third_party/googletest:gmock", + "//utils/native/base:utils", + "//base/update/updater/services/log:libupdaterlog", + "//base/update/updater/utils:libutils", + "//third_party/bounds_checking_function:libsec_static", + "//third_party/lz4:liblz4_static", + "//base/update/updater/interfaces/kits/misc_info:libmiscinfo", + "//base/update/updater/interfaces/kits/updaterkits:libupdaterkits", + "//base/update/updater/services/package:libupdaterpackage", + "//base/update/updater/interfaces/kits/packages:libpackageExt", + "//third_party/cJSON:cjson_static", + "//third_party/curl:curl", + "//third_party/openssl:crypto_source", + "//third_party/openssl:ssl_source", + "//third_party/libxml2:xml2", + "//base/startup/syspara_lite/interfaces/innerkits/native/syspara:syspara", + ] + + defines = ["UPDATER_UT", "UPDATER_API_TEST"] + + external_deps = [ + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + "ipc:ipc_core", + "startup_l2:syspara", + "hiviewdfx_hilog_native:libhilog", + ] + + cflags_cc = [ + "-fexceptions", + ] + + public_configs = [ ":utest_config" ] + install_enable = true + part_name = "updater" +} diff --git a/tests/unittest/update_client/client_stub.cpp b/tests/unittest/update_client/client_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6c71207d035cd8bf099f8c31c79b5e47c834ba35 --- /dev/null +++ b/tests/unittest/update_client/client_stub.cpp @@ -0,0 +1,532 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 "client_stub.h" +#include "gtest/gtest.h" +#include "log.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "node_api.h" +#include "node_api_types.h" +#include "securec.h" +#include "update_client.h" +#include "update_helper.h" +#include "update_session.h" + +using namespace updateClient; +using namespace std; +using namespace OHOS::update_engine; +static constexpr int NUMBER_2 = 2; + +TestNApiValue g_callback(napi_function, nullptr); + +uint32_t g_testSessionId = 0; +UpdateClient* g_testClient = nullptr; +static int32_t g_undefined = 100; +bool g_callbackFuncationCalled = false; + +static UpdatePolicy g_updatePolicy = { + true, + true, + INSTALLMODE_AUTO, + AUTOUPGRADECONDITION_IDLE, + {1000, 1000} +}; + +TestNApiEnv g_testEnv; + +static napi_value CreateNapiValue(int type, const void *value) +{ + auto testValue = new TestNApiValue(type, value); + g_testEnv.testValueList.push_back(testValue); + return (napi_value)testValue; +} + +void FreeAllNapiValues() +{ + auto iter = g_testEnv.testValueList.begin(); + while (iter != g_testEnv.testValueList.end()) { + auto value = *iter; + g_testEnv.testValueList.erase(iter); + delete value; + iter = g_testEnv.testValueList.begin(); + } +} + +TestNApiValue::TestNApiValue(int type, const void *value) +{ + type_ = type; + switch (type) { + case napi_boolean: + bValue = *static_cast(const_cast(value)); + break; + case napi_number: + intValue = *static_cast(const_cast(value)); + break; + case napi_string: + strValue = std::string(static_cast(const_cast(value))); + break; + case napi_bigint: + int64Value = *static_cast(const_cast(value)); + break; + default: + break; + } +} + +UpdateSession *TestGetUpdateSession() +{ + printf(" TestGetUpdateSession g_testSessionId %u\n", g_testSessionId); + if (g_testClient != nullptr) { + return g_testClient->GetUpdateSession(g_testSessionId); + } + return nullptr; +} + +#ifdef __cplusplus +extern "C" { +#endif + +napi_status napi_create_string_utf8(napi_env env, const char *str, size_t length, napi_value *result) +{ + *result = CreateNapiValue(napi_string, str); + return napi_status::napi_ok; +} + +napi_status napi_typeof(napi_env env, napi_value value, napi_valuetype *result) +{ + if (((TestNApiValue*)value)->GetType() == TEST_NVALUE_TYPE_CONTEXT) { + *result = napi_object; + } else if (((TestNApiValue*)value)->GetType() == TEST_NVALUE_TYPE_UPGRADE) { + *result = napi_object; + } else if (((TestNApiValue*)value)->GetType() == TEST_NVALUE_TYPE_UPDATE_POLICY) { + *result = napi_object; + } else { + *result = (napi_valuetype)((TestNApiValue*)value)->GetType(); + } + return napi_status::napi_ok; +} + +napi_status napi_create_reference(napi_env env, napi_value value, uint32_t initial_refcount, + napi_ref* result) +{ + return napi_status::napi_ok; +} + +napi_status napi_get_reference_value(napi_env env, napi_ref ref, napi_value* result) +{ + return napi_status::napi_ok; +} + +napi_status napi_delete_reference(napi_env env, napi_ref ref) +{ + return napi_status::napi_ok; +} + +napi_status napi_call_function(napi_env env, napi_value recv, + napi_value func, size_t argc, const napi_value *argv, napi_value *result) +{ + g_callbackFuncationCalled = true; + return napi_status::napi_ok; +} + +napi_status napi_delete_async_work(napi_env env, napi_async_work work) +{ + return napi_status::napi_ok; +} + +napi_status napi_queue_async_work(napi_env env, napi_async_work work) +{ + return napi_status::napi_ok; +} + +napi_status napi_cancel_async_work(napi_env env, napi_async_work work) +{ + return napi_status::napi_ok; +} + +napi_status napi_create_object(napi_env env, napi_value* result) +{ + *result = CreateNapiValue(napi_object, nullptr); + return napi_status::napi_ok; +} + +napi_status napi_set_element(napi_env env, napi_value object, uint32_t index, napi_value value) +{ + return napi_status::napi_ok; +} + +napi_status napi_create_array_with_length(napi_env env, size_t length, napi_value* result) +{ + *result = CreateNapiValue(napi_object, nullptr); + return napi_status::napi_ok; +} + +napi_status napi_create_int32(napi_env env, int32_t value, napi_value* result) +{ + *result = CreateNapiValue(napi_number, &value); + return napi_status::napi_ok; +} + +napi_status napi_create_uint32(napi_env env, uint32_t value, napi_value* result) +{ + *result = CreateNapiValue(napi_number, &value); + return napi_status::napi_ok; +} + +napi_status napi_get_undefined(napi_env env, napi_value* result) +{ + *result = (napi_value)&g_undefined; + return napi_status::napi_ok; +} + +napi_status napi_create_int64(napi_env env, int64_t value, napi_value* result) +{ + *result = CreateNapiValue(napi_bigint, &value); + return napi_status::napi_ok; +} + +napi_status napi_throw_error(napi_env env, const char* code, const char* msg) +{ + return napi_status::napi_ok; +} +napi_status napi_is_exception_pending(napi_env env, bool* result) +{ + return napi_status::napi_ok; +} + +napi_status napi_get_last_error_info(napi_env env, const napi_extended_error_info** result) +{ + return napi_status::napi_ok; +} + +napi_status napi_define_properties(napi_env env, napi_value object, + size_t property_count, const napi_property_descriptor *properties) +{ + return napi_status::napi_ok; +} + +void napi_module_register(napi_module* mod) {} + +napi_status napi_has_named_property(napi_env env, napi_value object, const char *utf8name, + bool *result) +{ + *result = false; + TestNApiValue* testValue = (TestNApiValue*)object; + if (testValue->GetType() == TEST_NVALUE_TYPE_CONTEXT) { + *result = true; + } else if (testValue->GetType() == TEST_NVALUE_TYPE_UPGRADE || + testValue->GetType() == TEST_NVALUE_TYPE_UPDATE_POLICY) { + *result = true; + } + return napi_status::napi_ok; +} + +napi_status napi_get_named_property(napi_env env, napi_value object, const char* utf8name, + napi_value* result) +{ + TestNApiEnv* testEnv = (TestNApiEnv*)env; + TestNApiValue* testValue = (TestNApiValue*)object; + + if (testValue->GetType() == TEST_NVALUE_TYPE_CONTEXT) { + if (strcmp(utf8name, "serverAddr") == 0) { + *result = CreateNapiValue(napi_string, "10.50.40.92"); + } else if (strcmp(utf8name, "upgradeDevId") == 0) { + *result = CreateNapiValue(napi_string, testEnv->clientContext.upgradeDevId.c_str()); + } else if (strcmp(utf8name, "controlDevId") == 0) { + *result = CreateNapiValue(napi_string, testEnv->clientContext.controlDevId.c_str()); + } else if (strcmp(utf8name, "upgradeApp") == 0) { + *result = CreateNapiValue(napi_string, testEnv->clientContext.upgradeApp.c_str()); + } else if (strcmp(utf8name, "type") == 0) { + *result = CreateNapiValue(napi_number, &testEnv->clientContext.type); + } + } else if (testValue->GetType() == TEST_NVALUE_TYPE_UPGRADE) { + if (strcmp(utf8name, "versionName") == 0) { + *result = CreateNapiValue(napi_string, testEnv->pakcageInfo.result[0].versionName.c_str()); + } else if (strcmp(utf8name, "versionCode") == 0) { + *result = CreateNapiValue(napi_string, testEnv->pakcageInfo.result[0].versionCode.c_str()); + } else if (strcmp(utf8name, "verifyInfo") == 0) { + *result = CreateNapiValue(napi_string, testEnv->pakcageInfo.result[0].verifyInfo.c_str()); + } else if (strcmp(utf8name, "descriptPackageId") == 0) { + *result = CreateNapiValue(napi_string, testEnv->pakcageInfo.result[0].descriptPackageId.c_str()); + } else if (strcmp(utf8name, "packageType") == 0) { + *result = CreateNapiValue(napi_number, &testEnv->pakcageInfo.result[0].packageType); + } else if (strcmp(utf8name, "size") == 0) { + *result = CreateNapiValue(napi_bigint, &testEnv->pakcageInfo.result[0].size); + } + } else if (testValue->GetType() == TEST_NVALUE_TYPE_UPDATE_POLICY) { + if (strcmp(utf8name, "autoDownload") == 0) { + *result = CreateNapiValue(napi_number, (void*)&g_updatePolicy.autoDownload); + } else if (strcmp(utf8name, "autoDownloadNet") == 0) { + *result = CreateNapiValue(napi_string, (void*)&g_updatePolicy.autoDownloadNet); + } else if (strcmp(utf8name, "mode") == 0) { + *result = CreateNapiValue(napi_string, (void*)&g_updatePolicy.mode); + } else if (strcmp(utf8name, "autoUpgradeCondition") == 0) { + *result = CreateNapiValue(napi_string, (void*)&g_updatePolicy.autoUpgradeCondition); + } + } + return napi_status::napi_ok; +} + +napi_status napi_get_value_string_utf8(napi_env env, napi_value value, char* buf, + size_t bufsize, size_t* result) +{ + TestNApiValue* testValue = (TestNApiValue*)value; + if (buf != nullptr) { + memcpy_s(buf, bufsize, testValue->strValue.data(), testValue->strValue.size()); + } + printf("napi_get_value_string_utf8 %s bufsize %zu %zu \n", + testValue->strValue.c_str(), bufsize, testValue->strValue.size()); + *result = testValue->strValue.size(); + return napi_status::napi_ok; +} + +napi_status napi_get_value_int32(napi_env env, napi_value value, int32_t* result) +{ + TestNApiValue* testValue = (TestNApiValue*)value; + *result = testValue->intValue; + return napi_status::napi_ok; +} + +napi_status napi_get_value_uint32(napi_env env, napi_value value, uint32_t* result) +{ + TestNApiValue* testValue = (TestNApiValue*)value; + *result = static_cast(testValue->intValue); + return napi_status::napi_ok; +} + +napi_status napi_get_value_int64(napi_env env, napi_value value, int64_t* result) +{ + TestNApiValue* testValue = (TestNApiValue*)value; + *result = testValue->int64Value; + return napi_status::napi_ok; +} + +napi_status napi_set_named_property(napi_env env, napi_value object, const char *utf8name, + napi_value value) +{ + TestNApiEnv* testEnv = (TestNApiEnv*)env; + TestNApiValue* testValue = (TestNApiValue*)value; + if (testValue == nullptr) { + return napi_status::napi_ok; + } + if (testValue->GetType() == napi_string) { + if (testValue->strValue.empty()) { + return napi_status::napi_ok; + } + if (strcmp(utf8name, "versionName") == 0) { + testEnv->pakcageInfo.result[0].versionName = testValue->strValue; + } else if (strcmp(utf8name, "versionCode") == 0) { + testEnv->pakcageInfo.result[0].versionCode = testValue->strValue; + } else if (strcmp(utf8name, "verifyInfo") == 0) { + testEnv->pakcageInfo.result[0].verifyInfo = testValue->strValue; + } else if (strcmp(utf8name, "descriptPackageId") == 0) { + if (testValue->strValue.size() > 0) { + testEnv->pakcageInfo.result[0].descriptPackageId = testValue->strValue; + } + } else if (strcmp(utf8name, "errMsg") == 0) { + testEnv->errorMsg = testValue->strValue; + } + } else if (testValue->GetType() == napi_number) { + if (strcmp(utf8name, "packageType") == 0) { + testEnv->pakcageInfo.result[0].packageType = (PackageType)testValue->intValue; + } else if (strcmp(utf8name, "status") == 0) { + testEnv->progress.status = (UpgradeStatus)testValue->intValue; + } else if (strcmp(utf8name, "percent") == 0) { + testEnv->progress.percent = testValue->intValue; + } + } else if (testValue->GetType() == napi_bigint) { + if (strcmp(utf8name, "size") == 0 && testValue->int64Value != 0) { + testEnv->pakcageInfo.result[0].size = (size_t)testValue->int64Value; + } + } + return napi_status::napi_ok; +} + +// Asynchronous execution +napi_status napi_create_async_work(napi_env env, napi_value async_resource, + napi_value async_resource_name, napi_async_execute_callback execute, + napi_async_complete_callback complete, void *data, napi_async_work *result) +{ + UpdateSession *sess = static_cast(data); + g_testSessionId = sess->GetSessionId(); + printf(" g_testSessionId %u\n", g_testSessionId); + *result = (napi_async_work)CreateNapiValue(0, nullptr); + return napi_status::napi_ok; +} + +napi_status napi_get_cb_info( + napi_env env, // [in] NAPI environment handle + napi_callback_info cbinfo, // [in] Opaque callback-info handle + size_t *argc, // [in-out] Specifies the size of the provided argv array + // and receives the actual count of args. + napi_value *argv, // [out] Array of values + napi_value *this_arg, // [out] Receives the JS 'this' arg for the call + void **data) // [out] Receives the data pointer for the callback. +{ + TestNApiEnv* testEnv = (TestNApiEnv*)env; + printf("++++++++++++++ napi_get_cb_info argc %zu testStage %d \n", *argc, testEnv->testStage); + switch (testEnv->testStage) { + case SESSION_GET_UPDATER: { + if (*argc > 1) { + *argc = (testEnv->engineType != 0) ? NUMBER_2 : 1; + argv[0] = CreateNapiValue(napi_string, "OTA"); + argv[1] = CreateNapiValue(napi_string, testEnv->eventType.c_str()); + } else { + argv[0] = CreateNapiValue(napi_string, "OTA"); + *argc = 1; + } + break; + } + case SESSION_VERIFY_PACKAGE:{ + if (*argc > 1) { + argv[0] = CreateNapiValue(napi_string, "/data/updater/updater/updater_success.zip"); + argv[1] = CreateNapiValue(napi_string, "/data/updater/src/signing_cert.crt"); + } + *argc = NUMBER_2; + break; + } + case SESSION_SET_POLICY: { + argv[0] = CreateNapiValue(TEST_NVALUE_TYPE_UPDATE_POLICY, nullptr); + if (*argc > 1) { + argv[1] = CreateNapiValue(napi_function, nullptr); + } + *argc = testEnv->testAsyncorPermose ? 1 : NUMBER_2; + break; + } + case SESSION_SUBSCRIBE: + case SESSION_UNSUBSCRIBE: { + argv[0] = CreateNapiValue(napi_string, testEnv->eventType.c_str()); + if (*argc > 1) { + argv[1] = CreateNapiValue(napi_function, nullptr); + } + *argc = testEnv->testAsyncorPermose ? 1 : NUMBER_2; + break; + } + default:{ + *argc = testEnv->testAsyncorPermose ? 0 : 1; + *argv = CreateNapiValue(napi_function, nullptr); + break; + } + } + return napi_status::napi_ok; +} + +napi_status napi_is_array(napi_env env, napi_value value, bool *result) +{ + *result = true; + return napi_status::napi_ok; +} + +napi_status napi_get_array_length(napi_env env, napi_value value, uint32_t *result) +{ + *result = sizeof(g_updatePolicy.autoUpgradeInterval) / sizeof(g_updatePolicy.autoUpgradeInterval[0]); + return napi_status::napi_ok; +} + +napi_status napi_get_element(napi_env env, napi_value object, uint32_t index, napi_value *result) +{ + if (index >= sizeof(g_updatePolicy.autoUpgradeInterval) / sizeof(g_updatePolicy.autoUpgradeInterval[0])) { + *result = nullptr; + return napi_status::napi_ok; + } + *result = CreateNapiValue(napi_number, &g_updatePolicy.autoUpgradeInterval[index]); + return napi_status::napi_ok; +} + +napi_status napi_open_handle_scope(napi_env env, napi_handle_scope* result) +{ + return napi_status::napi_ok; +} + +napi_status napi_close_handle_scope(napi_env env, napi_handle_scope scope) +{ + return napi_status::napi_ok; +} + +napi_status napi_get_value_bool(napi_env env, napi_value value, bool* result) +{ + *result = true; + return napi_status::napi_ok; +} + +napi_status napi_strict_equals(napi_env env, napi_value lhs, napi_value rhs, bool* result) +{ + *result = true; + return napi_status::napi_ok; +} + +napi_status napi_create_promise(napi_env env, napi_deferred* deferred, napi_value* promise) +{ + return napi_status::napi_ok; +} + +napi_status napi_resolve_deferred(napi_env env, napi_deferred deferred, napi_value resolution) +{ + return napi_status::napi_ok; +} + +napi_status napi_reject_deferred(napi_env env, napi_deferred deferred, napi_value rejection) +{ + return napi_status::napi_ok; +} + +// Methods to work with external data objects +napi_status napi_wrap(napi_env env, napi_value jsObject, + void* native_object, napi_finalize finalize_cb, void* finalize_hint, napi_ref* result) +{ + return napi_status::napi_ok; +} + +napi_status napi_unwrap(napi_env env, napi_value jsObject, void** result) +{ + TestNApiEnv* testEnv = (TestNApiEnv*)env; + if (testEnv->testStage && testEnv->noneClient) { + *result = nullptr; + testEnv->noneClient = false; + return napi_status::napi_ok; + } + if (g_testClient == nullptr) { + g_testClient = new UpdateClient(env, jsObject); + } + *result = g_testClient; + return napi_status::napi_ok; +} + +napi_status napi_define_class(napi_env env, const char* utf8name, size_t length, napi_callback constructor, + void* data, size_t property_count, const napi_property_descriptor* properties, napi_value* result) +{ + std::function func = constructor; + func(env, nullptr); + return napi_status::napi_ok; +} + +napi_status napi_new_instance(napi_env env, napi_value constructor, size_t argc, const napi_value* argv, + napi_value* result) +{ + return napi_status::napi_ok; +} + +napi_status napi_remove_wrap(napi_env env, napi_value js_object, void** result) +{ + return napi_status::napi_ok; +} + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/tests/unittest/update_client/client_stub.h b/tests/unittest/update_client/client_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..f8cc4df71492fc486b1db64c20f7f8c4ef2e816e --- /dev/null +++ b/tests/unittest/update_client/client_stub.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 CLIENT_STUB_H +#define CLIENT_STUB_H +#include +#include +#include +#include "gtest/gtest.h" +#include "log.h" +#include "update_client.h" +#include "update_helper.h" + +constexpr int32_t TEST_NVALUE_TYPE_CONTEXT = 1000; +constexpr int32_t TEST_NVALUE_TYPE_UPGRADE = 1001; +constexpr int32_t TEST_NVALUE_TYPE_UPDATE_POLICY = 1002; + +class TestNApiValue { +public: + TestNApiValue(int type, const void *value); + ~TestNApiValue() {} + + int GetType() + { + return type_; + } +public: + int type_; + bool bValue; + int intValue; + int64_t int64Value; + std::string strValue; +}; + +struct TestNApiEnv { + int testStage = 0; + bool testAsyncorPermose = true; + int engineType = 0; + bool noneClient = false; + OHOS::update_engine::UpdateContext clientContext; + OHOS::update_engine::VersionInfo pakcageInfo; + OHOS::update_engine::Progress progress; + std::string errorMsg; + std::string eventType; + // Save the applied memory and release it at last + std::vector testValueList; +}; + +updateClient::UpdateSession *TestGetUpdateSession(); +void FreeAllNapiValues(); +#endif // CLIENT_STUB_H diff --git a/tests/unittest/update_client/client_unittest.cpp b/tests/unittest/update_client/client_unittest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f924044c030124c93256735aa19de3d60661c39d --- /dev/null +++ b/tests/unittest/update_client/client_unittest.cpp @@ -0,0 +1,553 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 "client_stub.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include "iupdate_service.h" +#include "log.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "node_api.h" +#include "node_api_types.h" +#include "unittest_comm.h" +#include "update_helper.h" +#include "update_service.h" +#include "update_session.h" + +using namespace std; +using namespace updateClient; +using namespace OHOS::update_engine; +static constexpr int PERCENT_20 = 20; +static constexpr int PERCENT_40 = 40; +static constexpr int PERCENT_60 = 60; +static constexpr int PERCENT_100 = 100; +static constexpr int NUMBER_2 = 2; + +extern TestNApiEnv g_testEnv; +extern uint32_t g_testSessionId; +extern bool g_callbackFuncationCalled; +extern UpdateClient* g_testClient; + +namespace { +#define CHECK_RESULT_EQ(ret, value) EXPECT_EQ(((TestNApiValue*)(ret))->intValue, (value)); +const int32_t JSON_MAX_SIZE = 4096; + +class UpdateClientTest : public ::testing::Test { +public: + UpdateClientTest() {} + virtual ~UpdateClientTest() {} + + void SetUp() {} + void TearDown() {} + void TestBody() {} + + int GetJsonInfo(VersionInfo &info) const + { + std::string jsonFileName = TEST_PATH_FROM; + jsonFileName += "packageInfos.json"; + + std::vector buffer(JSON_MAX_SIZE); + FILE *fp = fopen(jsonFileName.c_str(), "r"); + CLIENT_CHECK(fp != nullptr, return -1, "parse json error %s", jsonFileName.c_str()); + size_t bytes = fread(buffer.data(), 1, JSON_MAX_SIZE, fp); + if (bytes > 0) { + int32_t ret = UpdateService::ParseJsonFile(buffer, info); + CLIENT_CHECK(ret == 0, return 0, "parse json error"); + } + return 0; + } + + int TestGetUpdate(bool noneClient) + { + g_testEnv.testStage = SESSION_GET_UPDATER; + g_testEnv.engineType = 0; + g_testEnv.noneClient = noneClient; + g_testEnv.eventType = "OTA"; + napi_value value = GetUpdater((napi_env)&g_testEnv, nullptr); + CLIENT_CHECK(value == nullptr, return -1, "TestGetUpdate"); + return 0; + } + + int TestGetUpdaterForOther(bool noneClient) + { + g_testEnv.testStage = SESSION_GET_UPDATER; + g_testEnv.engineType = 1; + g_testEnv.noneClient = noneClient; + g_testEnv.eventType = "OTA"; + napi_value value = GetUpdaterForOther((napi_env)&g_testEnv, nullptr); + CLIENT_CHECK(value == nullptr, return -1, "TestGetUpdate"); + return 0; + } + + int TestGetUpdaterFromOther(bool noneClient) + { + g_testEnv.testStage = SESSION_GET_UPDATER; + g_testEnv.engineType = NUMBER_2; + g_testEnv.noneClient = noneClient; + g_testEnv.eventType = "OTA"; + napi_value value = GetUpdaterFromOther((napi_env)&g_testEnv, nullptr); + CLIENT_CHECK(value == nullptr, return -1, "TestGetUpdate"); + return 0; + } + + int TestCheckNewVersion(bool isPormise) + { + g_testEnv.testStage = SESSION_CHECK_VERSION; + g_testEnv.testAsyncorPermose = isPormise; + napi_value value = CheckNewVersion((napi_env)&g_testEnv, nullptr); + EXPECT_NE(value, nullptr); + + // Trigger thread execution + UpdateSession *sess = TestGetUpdateSession(); + CLIENT_CHECK(sess != nullptr, return -1, "TestCheckNewVersion"); + UpdateResult result = {}; + sess->NotifyJS((napi_env)&g_testEnv, nullptr, 0, result); + UpdateSession::ExecuteWork((napi_env)&g_testEnv, (void*)sess); + + // Call back the search result and save the result information + VersionInfo info; + int ret = GetJsonInfo(info); + EXPECT_EQ(ret, 0); + g_testClient->NotifyCheckVersionDone(info); + + // end of execution + UpdateSession::CompleteWork((napi_env)&g_testEnv, napi_status::napi_ok, (void*)sess); + + // Check the data + CLIENT_LOGI("g_testEnv.pakcageInfo.versionCode %s \n", g_testEnv.pakcageInfo.result[0].versionCode.c_str()); + CLIENT_LOGI("info.result[0].versionCode %s \n", info.result[0].versionCode.c_str()); + + FreeAllNapiValues(); + return 0; + } + + int TestDownloadVersion(bool isPormise) + { + g_testEnv.testStage = SESSION_DOWNLOAD; + g_testEnv.testAsyncorPermose = isPormise; + napi_value value = DownloadVersion((napi_env)&g_testEnv, nullptr); + EXPECT_NE(value, nullptr); + + // Trigger thread execution + UpdateSession *sess = TestGetUpdateSession(); + CLIENT_CHECK(sess != nullptr, return -1, "TestDownloadVersion"); + UpdateSession::ExecuteWork((napi_env)&g_testEnv, (void*)sess); + + // Call back the download result and save the result information + Progress info; + info.percent = PERCENT_20; + info.status = UPDATE_STATE_DOWNLOAD_ON; + g_testClient->NotifyDownloadProgress(info); + + info.percent = PERCENT_40; + info.status = UPDATE_STATE_DOWNLOAD_ON; + g_testClient->NotifyDownloadProgress(info); + + info.percent = PERCENT_60; + info.status = UPDATE_STATE_DOWNLOAD_ON; + g_testClient->NotifyDownloadProgress(info); + + info.percent = PERCENT_100; + info.status = UPDATE_STATE_DOWNLOAD_SUCCESS; + g_testClient->NotifyDownloadProgress(info); + + // end of execution + UpdateSession::CompleteWork((napi_env)&g_testEnv, napi_status::napi_ok, (void*)sess); + + FreeAllNapiValues(); + return 0; + } + + int TestUpgradeVersion(bool isPormise) + { + g_testEnv.testStage = SESSION_UPGRADE; + g_testEnv.testAsyncorPermose = isPormise; + napi_value value = UpgradeVersion((napi_env)&g_testEnv, nullptr); + CLIENT_CHECK(value != nullptr, return -1, "UpgradeVersion"); + + // Trigger thread execution + UpdateSession *sess = TestGetUpdateSession(); + CLIENT_CHECK(sess != nullptr, return -1, "UpgradeVersion"); + UpdateSession::ExecuteWork((napi_env)&g_testEnv, (void*)sess); + + // Call back the download result and save the result information + Progress info; + info.percent = PERCENT_20; + info.status = UPDATE_STATE_DOWNLOAD_ON; + g_testClient->NotifyUpgradeProgresss(info); + + info.percent = PERCENT_40; + info.status = UPDATE_STATE_DOWNLOAD_ON; + g_testClient->NotifyUpgradeProgresss(info); + + info.percent = PERCENT_60; + info.status = UPDATE_STATE_DOWNLOAD_ON; + g_testClient->NotifyUpgradeProgresss(info); + + info.percent = PERCENT_100; + info.status = UPDATE_STATE_DOWNLOAD_SUCCESS; + g_testClient->NotifyUpgradeProgresss(info); + + // end of execution + UpdateSession::CompleteWork((napi_env)&g_testEnv, napi_status::napi_ok, (void*)sess); + + FreeAllNapiValues(); + return 0; + } + + int TestSetUpdatePolicy(bool isPormise) + { + g_testEnv.testStage = SESSION_SET_POLICY; + g_testEnv.testAsyncorPermose = isPormise; + napi_value value = SetUpdatePolicy((napi_env)&g_testEnv, nullptr); + EXPECT_NE(value, nullptr); + + printf("TestSetUpdatePolicy \n"); + // Trigger thread execution + UpdateSession *sess = TestGetUpdateSession(); + CLIENT_CHECK(sess != nullptr, return -1, "TestSetUpdatePolicy"); + UpdateSession::ExecuteWork((napi_env)&g_testEnv, (void*)sess); + // end of execution + UpdateSession::CompleteWork((napi_env)&g_testEnv, napi_status::napi_ok, (void*)sess); + + FreeAllNapiValues(); + return 0; + } + + int TestGetUpdatePolicy(bool isPormise) + { + g_testEnv.testStage = SESSION_GET_POLICY; + g_testEnv.testAsyncorPermose = isPormise; + napi_value value = GetUpdatePolicy((napi_env)&g_testEnv, nullptr); + EXPECT_NE(value, nullptr); + + // Trigger thread execution + UpdateSession *sess = TestGetUpdateSession(); + CLIENT_CHECK(sess != nullptr, return -1, "TestGetUpdatePolicy"); + UpdateSession::ExecuteWork((napi_env)&g_testEnv, (void*)sess); + // end of execution + UpdateSession::CompleteWork((napi_env)&g_testEnv, napi_status::napi_ok, (void*)sess); + + FreeAllNapiValues(); + return 0; + } + + int TestGetNewVersionInfo(bool isPormise) + { + g_testEnv.testStage = SESSION_GET_NEW_VERSION; + g_testEnv.testAsyncorPermose = isPormise; + napi_value value = GetNewVersionInfo((napi_env)&g_testEnv, nullptr); + EXPECT_NE(value, nullptr); + // Trigger thread execution + UpdateSession *sess = TestGetUpdateSession(); + CLIENT_CHECK(sess != nullptr, return -1, "TestGetNewVersionInfo"); + UpdateSession::ExecuteWork((napi_env)&g_testEnv, (void*)sess); + // end of execution + UpdateSession::CompleteWork((napi_env)&g_testEnv, napi_status::napi_ok, (void*)sess); + + FreeAllNapiValues(); + return 0; + } + + int TestGetUpgradeStatus(bool isPormise) + { + g_testEnv.testStage = SESSION_GET_STATUS; + g_testEnv.testAsyncorPermose = isPormise; + napi_value value = GetUpgradeStatus((napi_env)&g_testEnv, nullptr); + EXPECT_NE(value, nullptr); + + // Trigger thread execution + UpdateSession *sess = TestGetUpdateSession(); + CLIENT_CHECK(sess != nullptr, return -1, "TestGetUpgradeStatus"); + UpdateSession::ExecuteWork((napi_env)&g_testEnv, (void*)sess); + // end of execution + UpdateSession::CompleteWork((napi_env)&g_testEnv, napi_status::napi_ok, (void*)sess); + + FreeAllNapiValues(); + return 0; + } + + int TestApplyNewVersion(bool isPormise) + { + g_testEnv.testStage = SESSION_APPLY_NEW_VERSION; + g_testEnv.testAsyncorPermose = isPormise; + napi_value value = ApplyNewVersion((napi_env)&g_testEnv, nullptr); + EXPECT_NE(value, nullptr); + + // Trigger thread execution + UpdateSession *sess = TestGetUpdateSession(); + CLIENT_CHECK(sess != nullptr, return -1, "TestApplyNewVersion"); + UpdateSession::ExecuteWork((napi_env)&g_testEnv, (void*)sess); + // end of execution + UpdateSession::CompleteWork((napi_env)&g_testEnv, napi_status::napi_ok, (void*)sess); + + FreeAllNapiValues(); + return 0; + } + + int TestRebootAndClean(bool isPormise) + { + g_testEnv.testStage = SESSION_REBOOT_AND_CLEAN; + g_testEnv.testAsyncorPermose = isPormise; + napi_value value = RebootAndClean((napi_env)&g_testEnv, nullptr); + EXPECT_NE(value, nullptr); + + // Trigger thread execution + UpdateSession *sess = TestGetUpdateSession(); + CLIENT_CHECK(sess != nullptr, return -1, "TestRebootAndClean"); + UpdateSession::ExecuteWork((napi_env)&g_testEnv, (void*)sess); + // end of execution + UpdateSession::CompleteWork((napi_env)&g_testEnv, napi_status::napi_ok, (void*)sess); + + FreeAllNapiValues(); + return 0; + } + + int TestVerifyUpdatePackage(bool isPormise) + { + g_testEnv.testStage = SESSION_VERIFY_PACKAGE; + g_testEnv.testAsyncorPermose = isPormise; + napi_value value = VerifyUpdatePackage((napi_env)&g_testEnv, nullptr); + EXPECT_NE(value, nullptr); + // Trigger thread execution + UpdateSession *sess = TestGetUpdateSession(); + CLIENT_CHECK(sess != nullptr, return -1, "TestVerifyUpdatePackage"); + UpdateSession *sess1 = static_cast(sess); + EXPECT_NE(sess1, nullptr); + sess1->UpdateSession::CompleteWork((napi_env)&g_testEnv, napi_status::napi_ok); + UpdateSession::ExecuteWork((napi_env)&g_testEnv, (void*)sess); + + // Call back the download result and save the result information + g_testClient->NotifyVerifyProgresss(0, PERCENT_60); + g_testClient->NotifyVerifyProgresss(0, PERCENT_100); + + // end of execution + UpdateSession::CompleteWork((napi_env)&g_testEnv, napi_status::napi_ok, (void*)sess); + FreeAllNapiValues(); + return 0; + } + + int TestSubscribeEvent(const std::string &eventType) + { + g_testEnv.testStage = SESSION_SUBSCRIBE; + g_testEnv.testAsyncorPermose = false; + g_testEnv.eventType = eventType; + napi_value value = SubscribeEvent((napi_env)&g_testEnv, nullptr); + CLIENT_CHECK(value != nullptr, return -1, "TestSubscribeEvent"); + + Progress info; + info.percent = PERCENT_20; + info.status = UPDATE_STATE_DOWNLOAD_ON; + g_testClient->NotifyUpgradeProgresss(info); + + info.percent = PERCENT_40; + info.status = UPDATE_STATE_DOWNLOAD_ON; + g_testClient->NotifyUpgradeProgresss(info); + + info.percent = PERCENT_60; + info.status = UPDATE_STATE_DOWNLOAD_ON; + g_testClient->NotifyDownloadProgress(info); + + info.percent = PERCENT_100; + info.status = UPDATE_STATE_DOWNLOAD_SUCCESS; + g_testClient->NotifyDownloadProgress(info); + FreeAllNapiValues(); + return 0; + } + + int TestUnsubscribeEvent(bool isPormise, const std::string &eventType) + { + g_testEnv.testStage = SESSION_UNSUBSCRIBE; + g_testEnv.testAsyncorPermose = isPormise; + g_testEnv.eventType = eventType; + napi_value value = UnsubscribeEvent((napi_env)&g_testEnv, nullptr); + CLIENT_CHECK(value != nullptr, return -1, "TestUnsubscribeEvent"); + + FreeAllNapiValues(); + return 0; + } + + int TestCancelUpgrade(int type) + { + g_testEnv.testStage = SESSION_CANCEL_UPGRADE; + g_testEnv.testAsyncorPermose = false; + napi_value value = CancelUpgrade((napi_env)&g_testEnv, nullptr); + CLIENT_CHECK(value != nullptr, return -1, "TestCancelUpgrade"); + + // Trigger thread execution + UpdateSession *sess = TestGetUpdateSession(); + CLIENT_CHECK(sess != nullptr, return -1, "TestCancelUpgrade"); + UpdateSession::ExecuteWork((napi_env)&g_testEnv, (void*)sess); + // end of execution + UpdateSession::CompleteWork((napi_env)&g_testEnv, napi_status::napi_ok, (void*)sess); + + FreeAllNapiValues(); + return 0; + } +}; + +TEST(UpdateClientTest, TestGetUpdate) +{ + napi_value exports = nullptr; + UpdateClientInit((napi_env)&g_testEnv, exports); + UpdateClientTest test; + test.TestGetUpdate(false); + test.TestGetUpdaterFromOther(false); + test.TestGetUpdaterForOther(false); +} + +TEST(UpdateClientTest, TestGetUpdate2) +{ + UpdateClientTest test; + test.TestGetUpdate(true); + test.TestGetUpdaterFromOther(true); + test.TestGetUpdaterForOther(true); +} + +TEST(UpdateClientTest, TestCheckNewVersion) +{ + UpdateClientTest test; + test.TestGetUpdate(false); + EXPECT_EQ(0, test.TestCheckNewVersion(false)); + EXPECT_EQ(0, test.TestCheckNewVersion(true)); +} + +TEST(UpdateClientTest, TestDownloadVersion) +{ + UpdateClientTest test; + EXPECT_EQ(0, test.TestDownloadVersion(false)); + EXPECT_EQ(0, test.TestDownloadVersion(true)); +} + +TEST(UpdateClientTest, TestUpgradeVersion) +{ + UpdateClientTest test; + EXPECT_EQ(0, test.TestUpgradeVersion(false)); + EXPECT_EQ(0, test.TestUpgradeVersion(true)); +} + +TEST(UpdateClientTest, TestSetUpdatePolicy) +{ + UpdateClientTest test; + EXPECT_EQ(0, test.TestSetUpdatePolicy(false)); + EXPECT_EQ(0, test.TestSetUpdatePolicy(true)); +} + +TEST(UpdateClientTest, TestGetUpdatePolicy) +{ + UpdateClientTest test; + EXPECT_EQ(0, test.TestGetUpdatePolicy(false)); + EXPECT_EQ(0, test.TestGetUpdatePolicy(true)); +} + +TEST(UpdateClientTest, TestGetUpgradeStatus) +{ + UpdateClientTest test; + EXPECT_EQ(0, test.TestGetUpgradeStatus(false)); + EXPECT_EQ(0, test.TestGetUpgradeStatus(true)); +} + +TEST(UpdateClientTest, TestGetNewVersionInfo) +{ + UpdateClientTest test; + EXPECT_EQ(0, test.TestGetNewVersionInfo(false)); + EXPECT_EQ(0, test.TestGetNewVersionInfo(true)); +} + +TEST(UpdateClientTest, TestApplyNewVersion) +{ + UpdateClientTest test; + EXPECT_EQ(0, test.TestApplyNewVersion(false)); + EXPECT_EQ(0, test.TestApplyNewVersion(true)); +} + +TEST(UpdateClientTest, TestRebootAndClean) +{ + UpdateClientTest test; + EXPECT_EQ(0, test.TestRebootAndClean(false)); + EXPECT_EQ(0, test.TestRebootAndClean(true)); +} + +TEST(UpdateClientTest, TestVerifyUpdatePackage) +{ + UpdateClientTest test; + EXPECT_EQ(0, test.TestVerifyUpdatePackage(false)); + EXPECT_EQ(0, test.TestVerifyUpdatePackage(true)); +} + +TEST(UpdateClientTest, TestSubscribeEvent) +{ + UpdateClientTest test; + EXPECT_EQ(0, test.TestSubscribeEvent("downloadProgress")); + EXPECT_EQ(0, test.TestUnsubscribeEvent(false, "downloadProgress")); +} + +TEST(UpdateClientTest, TestSubscribeEvent2) +{ + UpdateClientTest test; + EXPECT_EQ(0, test.TestSubscribeEvent("downloadProgress")); + EXPECT_EQ(0, test.TestUnsubscribeEvent(true, "downloadProgress")); +} + +TEST(UpdateClientTest, TestSubscribeEvent3) +{ + UpdateClientTest test; + EXPECT_EQ(0, test.TestSubscribeEvent("upgradeProgress")); + EXPECT_EQ(0, test.TestUnsubscribeEvent(false, "upgradeProgress")); +} + +TEST(UpdateClientTest, TestSubscribeEvent4) +{ + UpdateClientTest test; + EXPECT_EQ(0, test.TestSubscribeEvent("upgradeProgress")); + EXPECT_EQ(0, test.TestUnsubscribeEvent(true, "upgradeProgress")); +} + +TEST(UpdateClientTest, TestCancelUpgrade) +{ + UpdateClientTest test; + EXPECT_EQ(0, test.TestCancelUpgrade(2)); + EXPECT_EQ(0, test.TestCancelUpgrade(3)); +} + +TEST(UpdateClientTest, TestNewClient) +{ + napi_value thisVar = nullptr; + UpdateClient *client = new UpdateClient((napi_env)&g_testEnv, thisVar); + delete client; +} + +TEST(UpdateClientTest, TestUpdateAsyncessionNoCallback) +{ + UpdateSession *sess = new UpdateAsyncessionNoCallback(g_testClient, 2, 1, 0); + EXPECT_NE(sess, nullptr); + delete sess; +} + +TEST(UpdateClientTest, TestUpdatePromiseSession) +{ + UpdateSession *sess = new UpdatePromiseSession (g_testClient, 2, 1, 0); + EXPECT_NE(sess, nullptr); + delete sess; +} +} // namespace diff --git a/tests/unittest/update_engine/server_unittest.cpp b/tests/unittest/update_engine/server_unittest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..566adaa404d80cbc2f9af5230104209f791f7acc --- /dev/null +++ b/tests/unittest/update_engine/server_unittest.cpp @@ -0,0 +1,607 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 +#include +#include "cJSON.h" +#include "if_system_ability_manager.h" +#include "ipc_types.h" +#include "iservice_registry.h" +#include "iupdate_callback.h" +#include "iupdate_service.h" +#include "unittest_comm.h" +#include "update_callback.h" +#include "update_callback_proxy.h" +#include "update_helper.h" +#include "update_service.h" +#include "update_service_kits_impl.h" +#include "update_service_proxy.h" + +using namespace std; +using namespace OHOS; +using namespace OHOS::update_engine; +static const int32_t DLNOW_10 = 10; +static const int32_t DLNOW_20 = 20; +static const int32_t DLNOW_50 = 50; +static const int32_t DLNOW_70 = 70; +static const int32_t DLNOW_80 = 80; +static const int32_t DLTOTAL_NUM = 100; +static const int32_t UPGRADE_INTERVAL_2 = 2222; +static const int32_t UPGRADE_INTERVAL_3 = 3333; +static const int32_t JSON_MAX_SIZE = 4096; +#define UNUSED(x) (void)(x) +static UpdateService *GetUpdateService() +{ + static UpdateService *updateServer = nullptr; + if (updateServer == nullptr) { + updateServer = new UpdateService(0, true); + } + return updateServer; +} + +class UpdateServerTest : public ::testing::Test { +public: + UpdateServerTest() + { + updateServer_ = GetUpdateService(); + } + virtual ~UpdateServerTest() {} + + void SetUp() + { + updateCallBack_ = new UpdateCallback(); + } + void TearDown() + { + delete updateCallBack_; + } + void TestBody() {} + + int TestRegisterCallback() + { + return 0; + } + + int TestCheckNewVersion() + { + ENGINE_CHECK(updateServer_ != nullptr, return -1, "Can not find server"); + MessageParcel inData; + MessageParcel reply; + MessageOption msgOption; + updateServer_->OnRemoteRequest(IUpdateService::CHECK_VERSION, inData, reply, msgOption); + return 0; + } + + int TestDownload() + { + ENGINE_CHECK(updateServer_ != nullptr, return -1, "Can not find server"); + MessageParcel inData; + MessageParcel reply; + MessageOption msgOption; + updateServer_->OnRemoteRequest(IUpdateService::DOWNLOAD, inData, reply, msgOption); + EXPECT_EQ(0, reply.ReadInt32()); + sleep(1); + updateServer_->OnRemoteRequest(IUpdateService::CANCEL, inData, reply, msgOption); + return 0; + } + + int TestDoUpdate() + { + ENGINE_CHECK(updateServer_ != nullptr, return -1, "Can not find server"); + MessageParcel inData; + MessageParcel reply; + MessageOption msgOption; + updateServer_->OnRemoteRequest(IUpdateService::UPGRADE, inData, reply, msgOption); + EXPECT_EQ(0, reply.ReadInt32()); + return 0; + } + + int TestGetUpdatePolicy(UpdatePolicy &policy) + { + MessageParcel inData; + MessageParcel reply; + MessageOption msgOption; + updateServer_->OnRemoteRequest(IUpdateService::GET_POLICY, inData, reply, msgOption); + UpdateHelper::ReadUpdatePolicy(reply, policy); + return 0; + } + + int TestUpdatePolicy() + { + ENGINE_CHECK(updateServer_ != nullptr, return -1, "Can not find server"); + UpdatePolicy policy; + policy.autoDownload = true; + policy.autoDownloadNet = true; + policy.mode = INSTALLMODE_AUTO; + policy.autoUpgradeInterval[0] = UPGRADE_INTERVAL_2; + policy.autoUpgradeInterval[1] = UPGRADE_INTERVAL_3; + MessageParcel inData; + UpdateHelper::WriteUpdatePolicy(inData, policy); + MessageParcel reply; + MessageOption msgOption; + updateServer_->OnRemoteRequest(IUpdateService::SET_POLICY, inData, reply, msgOption); + UpdatePolicy policy2; + TestGetUpdatePolicy(policy2); + EXPECT_EQ(policy.autoUpgradeInterval[0], policy2.autoUpgradeInterval[0]); + return 0; + } + + int TestGetNewVersion() + { + VersionInfo versionInfo; + MessageParcel inData; + MessageParcel reply; + MessageOption msgOption; + updateServer_->OnRemoteRequest(IUpdateService::GET_NEW_VERSION, inData, reply, msgOption); + UpdateHelper::ReadVersionInfo(reply, versionInfo); + EXPECT_EQ(versionInfo.status, HAS_NEW_VERSION); + return 0; + } + + int TestGetUpgradeStatus() + { + UpgradeInfo info; + MessageParcel inData; + MessageParcel reply; + MessageOption msgOption; + updateServer_->OnRemoteRequest(IUpdateService::GET_STATUS, inData, reply, msgOption); + UpdateHelper::ReadUpgradeInfo(reply, info); + return 0; + } + + int TestRebootAndClean() + { + VersionInfo versionInfo; + MessageParcel inData; + MessageParcel reply; + MessageOption msgOption; + updateServer_->OnRemoteRequest(IUpdateService::REBOOT_CLEAN, inData, reply, msgOption); + EXPECT_EQ(reply.ReadInt32(), 0); + return 0; + } + + int TestRebootAndInstall() + { + VersionInfo versionInfo; + MessageParcel inData; + MessageParcel reply; + MessageOption msgOption; + updateServer_->OnRemoteRequest(IUpdateService::REBOOT_INSTALL, inData, reply, msgOption); + EXPECT_EQ(reply.ReadInt32(), 0); + return 0; + } + + int TestRegisterUpdateCallback() + { + VersionInfo versionInfo; + MessageParcel inData; + MessageParcel reply; + MessageOption msgOption; + updateServer_->OnRemoteRequest(IUpdateService::REGISTER_CALLBACK, inData, reply, msgOption); + EXPECT_EQ(reply.ReadInt32(), -1); + return 0; + } + + int TestUnRegisterUpdateCallback() + { + VersionInfo versionInfo; + MessageParcel inData; + MessageParcel reply; + MessageOption msgOption; + updateServer_->OnRemoteRequest(IUpdateService::UNREGISTER_CALLBACK, inData, reply, msgOption); + EXPECT_EQ(reply.ReadInt32(), 0); + return 0; + } + + int TestReadCheckVersiondescriptInfo() + { + cJSON *temp = cJSON_CreateObject(); + EXPECT_NE(temp, nullptr); + cJSON_AddStringToObject(temp, "descriptPackageId", "descriptPackageId1"); + cJSON_AddStringToObject(temp, "content", "content1"); + cJSON_AddNumberToObject(temp, "id", 1); + cJSON* array = cJSON_CreateArray(); + EXPECT_NE(array, nullptr); + cJSON_AddItemToArray(array, temp); + + VersionInfo info {}; + updateServer_->ReadCheckVersiondescriptInfo(array, info); + EXPECT_STREQ(info.descriptInfo[0].descriptPackageId.c_str(), "descriptPackageId1"); + EXPECT_STREQ(info.descriptInfo[0].content.c_str(), "content1"); + return 0; + } + + int TestUpdateServiceProxy() + { + sptr systemMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + EXPECT_NE(systemMgr, nullptr); + sptr remoteObj = systemMgr->GetSystemAbility(UPDATE_DISTRIBUTED_SERVICE_ID); + EXPECT_NE(remoteObj, nullptr); + UpdateServiceProxy *proxy = new UpdateServiceProxy(remoteObj); + UpdateCallbackProxy *updateCallBack = new UpdateCallbackProxy(remoteObj); + VersionInfo info {}; + Progress progress {}; + UpdateContext ctx {}; + updateCallBack->OnCheckVersionDone(info); + updateCallBack->OnDownloadProgress(progress); + updateCallBack->OnUpgradeProgress(progress); + proxy->RegisterUpdateCallback(ctx, updateCallBack); + proxy->UnregisterUpdateCallback(); + proxy->DoUpdate(); + EXPECT_EQ(info.status, HAS_NEW_VERSION); + EXPECT_EQ(progress.status, UPDATE_STATE_INIT); + delete proxy; + return 0; + } + + int TestUpdateCallbackCheckNewVersion() + { + MessageParcel inData; + MessageParcel reply; + MessageOption msgOption; + updateCallBack_->OnRemoteRequest(IUpdateService::CHECK_VERSION, inData, reply, msgOption); + EXPECT_EQ(reply.ReadInt32(), 0); + return 0; + } + + int TestUpdateCallbackDownload() + { + MessageParcel inData; + MessageParcel reply; + MessageOption msgOption; + updateCallBack_->OnRemoteRequest(IUpdateService::DOWNLOAD, inData, reply, msgOption); + EXPECT_EQ(reply.ReadInt32(), 0); + return 0; + } + + int TestUpdateCallbackUpgrade() + { + MessageParcel inData; + MessageParcel reply; + MessageOption msgOption; + updateCallBack_->OnRemoteRequest(IUpdateService::UPGRADE, inData, reply, msgOption); + EXPECT_EQ(reply.ReadInt32(), 0); + return 0; + } + + int TestDownLoadProgress() + { + DownloadThread *download = new DownloadThread( + [&](const std::string &filaName, const Progress &progress) -> int { + return 0; + }); + EXPECT_EQ(download == 0, 0); + std::string serverAddr; + UpdateService::GetServerIp(serverAddr); + std::string url = "http://"; + url += serverAddr; + url += "/updater.zip"; + download->StartDownload("updater.zip", url); + DownloadThread::DownloadProgress(download, DLTOTAL_NUM, DLNOW_10, 0, 0); + DownloadThread::DownloadProgress(download, DLTOTAL_NUM, DLNOW_20, 0, 0); + DownloadThread::DownloadProgress(download, DLTOTAL_NUM, DLNOW_50, 0, 0); + DownloadThread::DownloadProgress(download, DLTOTAL_NUM, DLNOW_70, 0, 0); + download->StopDownload(); + DownloadThread::DownloadProgress(download, DLTOTAL_NUM, DLNOW_80, 0, 0); + DownloadThread::DownloadProgress(download, DLTOTAL_NUM, DLTOTAL_NUM, 0, 0); + + // get file + std::string jsonFileName = TEST_PATH_FROM; + jsonFileName += "packageInfos.json"; + size_t length = DownloadThread::GetLocalFileLength(jsonFileName); + // write file + FILE *downloadFile = fopen("packageInfos.json", "ab+"); + if (downloadFile != nullptr) { + VersionInfo versionInfo {}; + std::vector buffer(JSON_MAX_SIZE); + fread(buffer.data(), 1, JSON_MAX_SIZE, downloadFile); + UpdateService::ParseJsonFile(buffer, versionInfo); + DownloadThread::WriteFunc((void *)buffer.data(), length, 1, downloadFile); + } + sleep(1); + delete download; + return 0; + } + + int TestNewUpdateService() + { + UpdateService *updateServer = new UpdateService(0, true); + updateServer->OnStart(); + updateServer->OnStop(); + delete updateServer; + return 0; + } + +private: + UpdateService *updateServer_ = nullptr; + UpdateCallback *updateCallBack_ = nullptr; +}; + +class MockUpdateServiceKits : public UpdateServiceKits { +public: + MockUpdateServiceKits() = default; + virtual ~MockUpdateServiceKits() = default; + + virtual int32_t RegisterUpdateCallback(const UpdateContext &ctx, const UpdateCallbackInfo &cb) override + { + UNUSED(ctx); + UNUSED(cb); + return 0; + } + + virtual int32_t UnregisterUpdateCallback() override + { + return 0; + } + + virtual int32_t CheckNewVersion() override + { + return 0; + } + + virtual int32_t DownloadVersion() override + { + return 0; + } + + virtual int32_t DoUpdate() override + { + return 0; + } + + virtual int32_t GetNewVersion(VersionInfo &versionInfo) override + { + UNUSED(versionInfo); + return 0; + } + + virtual int32_t GetUpgradeStatus(UpgradeInfo &info) override + { + UNUSED(info); + return 0; + } + + virtual int32_t SetUpdatePolicy(const UpdatePolicy &policy) override + { + UNUSED(policy); + return 0; + } + + virtual int32_t GetUpdatePolicy(UpdatePolicy &policy) override + { + UNUSED(policy); + return 0; + } + + virtual int32_t Cancel(int32_t service) override + { + return service; + } + + virtual int32_t RebootAndClean(const std::string &miscFile, const std::string &cmd) + { + UNUSED(miscFile); + UNUSED(cmd); + return 0; + } + + virtual int32_t RebootAndInstall(const std::string &miscFile, const std::string &packageName) + { + UNUSED(miscFile); + UNUSED(packageName); + return 0; + } +}; + +TEST(UpdateServerTest, TestDownload) +{ + UpdateServerTest test; + test.TestCheckNewVersion(); + test.TestDownload(); +} + +TEST(UpdateServerTest, TestDoUpdate) +{ + UpdateServerTest test; + test.TestDoUpdate(); +} + +TEST(UpdateServerTest, TestGetNewVersion) +{ + UpdateServerTest test; + test.TestCheckNewVersion(); + test.TestGetNewVersion(); +} + +TEST(UpdateServerTest, TestUpdatePolicy) +{ + UpdateServerTest test; + test.TestUpdatePolicy(); +} + +TEST(UpdateServerTest, TestGetUpgradeStatus) +{ + UpdateServerTest test; + test.TestGetUpgradeStatus(); +} + +TEST(UpdateServerTest, TestRebootAndClean) +{ + UpdateServerTest test; + test.TestRebootAndClean(); +} + +TEST(UpdateServerTest, TestRebootAndInstall) +{ + UpdateServerTest test; + test.TestRebootAndInstall(); +} + +TEST(UpdateServerTest, TestRegisterUpdateCallback) +{ + UpdateServerTest test; + test.TestRegisterUpdateCallback(); +} + +TEST(UpdateServerTest, TestUnRegisterUpdateCallback) +{ + UpdateServerTest test; + test.TestUnRegisterUpdateCallback(); +} + +TEST(UpdateServerTest, TestReadCheckVersiondescriptInfo) +{ + UpdateServerTest test; + test.TestReadCheckVersiondescriptInfo(); +} + +TEST(UpdateServerTest, TestUpdateCallbackCheckNewVersion) +{ + UpdateServerTest test; + test.TestUpdateCallbackCheckNewVersion(); +} + +TEST(UpdateServerTest, TestUpdateCallbackDownload) +{ + UpdateServerTest test; + test.TestUpdateCallbackDownload(); +} + +TEST(UpdateServerTest, TestUpdateCallbackUpgrade) +{ + UpdateServerTest test; + test.TestUpdateCallbackUpgrade(); +} + +TEST(UpdateServerTest, TestDownLoadProgress) +{ + UpdateServerTest test; + test.TestDownLoadProgress(); +} + +TEST(UpdateServerTest, TestNewUpdateService) +{ + UpdateServerTest test; + test.TestNewUpdateService(); +} + +TEST(UpdateServerTest, TestUpdateServiceProxy) +{ + UpdateServerTest test; + test.TestUpdateServiceProxy(); +} + +TEST(UpdateServerTest, TestKitsResetService) +{ + sptr systemMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + EXPECT_NE(systemMgr, nullptr); + sptr remoteObj = systemMgr->GetSystemAbility(UPDATE_DISTRIBUTED_SERVICE_ID); + EXPECT_NE(remoteObj, nullptr); + sptr deathRecipient = new UpdateServiceKitsImpl::DeathRecipient(); + deathRecipient->OnRemoteDied(remoteObj); + EXPECT_NE(deathRecipient, nullptr); + UpdateService *saServer = new UpdateService(0, true); + EXPECT_NE(saServer, nullptr); + const std::string miscFile = "/dev/block/platform/soc/10100000.himci.eMMC/by-name/misc"; + const std::string packageName = "--update_package=/data/updater/updater.zip"; + int32_t ret = saServer->RebootAndInstall(miscFile, packageName); + EXPECT_EQ(ret, 0); + delete saServer; +} + +TEST(UpdateServerTest, TestKitsRemoteCallbackOnCheckVersionDone) +{ + VersionInfo info {}; + UpdateCallbackInfo callBackFun {}; + sptr remoteCallBack = + new UpdateServiceKitsImpl::RemoteUpdateCallback(callBackFun); + remoteCallBack->OnCheckVersionDone(info); + EXPECT_NE(remoteCallBack, nullptr); +} + +TEST(UpdateServerTest, TestKitsRemoteCallbackOnDownloadProgress) +{ + Progress progress {}; + UpdateCallbackInfo callBackFun {}; + sptr remoteCallBack = + new UpdateServiceKitsImpl::RemoteUpdateCallback(callBackFun); + remoteCallBack->OnDownloadProgress(progress); + EXPECT_NE(remoteCallBack, nullptr); +} + +TEST(UpdateServerTest, TestKitsRemoteCallbackOnUpgradeProgress) +{ + Progress progress {}; + UpdateCallbackInfo callBackFun {}; + sptr remoteCallBack = + new UpdateServiceKitsImpl::RemoteUpdateCallback(callBackFun); + remoteCallBack->OnUpgradeProgress(progress); + EXPECT_NE(remoteCallBack, nullptr); +} + +TEST(UpdateServerTest, TestKitsRegisterUpdateCallback) +{ + UpdateCallbackInfo callBackFun {}; + UpdateContext ctx {}; + int ret = UpdateServiceKits::GetInstance().RegisterUpdateCallback(ctx, callBackFun); + EXPECT_EQ(ret, 0); + ret = UpdateServiceKits::GetInstance().UnregisterUpdateCallback(); + EXPECT_EQ(ret, 0); +} + +TEST(UpdateServerTest, TestKitsDoUpdate) +{ + int ret = UpdateServiceKits::GetInstance().DoUpdate(); + EXPECT_EQ(ret, 0); +} + +TEST(UpdateServerTest, TestKitsCancel) +{ + int32_t service = 0; + int ret = UpdateServiceKits::GetInstance().Cancel(service); + EXPECT_EQ(ret, 0); +} + +TEST(UpdateServerTest, TestKitsRebootAndClean) +{ + const std::string miscFile = "/dev/block/platform/soc/10100000.himci.eMMC/by-name/misc"; + const std::string cmd = "--update_package=/data/updater/updater.zip"; + int ret = UpdateServiceKits::GetInstance().RebootAndClean(miscFile, cmd); + EXPECT_NE(ret, 0); +} + +TEST(UpdateServerTest, TestKitsReadDataFromSSL) +{ + int32_t engineSocket = 10; + UpdateService *updateServer = new UpdateService(0, true); + EXPECT_NE(updateServer, nullptr); + updateServer->ReadDataFromSSL(engineSocket); + delete updateServer; +} + +TEST(UpdateServerTest, TestKits) +{ + UpdateServiceKits *kit = new MockUpdateServiceKits(); + EXPECT_NE(kit, nullptr); + delete kit; +} diff --git a/tests/unittest/update_server_ut_entry.cpp b/tests/unittest/update_server_ut_entry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b51108ba203a83e0ffdc09d74757336839e32635 --- /dev/null +++ b/tests/unittest/update_server_ut_entry.cpp @@ -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. + */ + +#include +#include +#include + +using namespace testing::ext; + +int main(int argc, char* argv[]) +{ + testing::InitGoogleMock(&argc, argv); + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} \ No newline at end of file