diff --git a/ai/BUILD.gn b/ai/BUILD.gn index 2e1cca99adfce48d484d620fad37a049bb3a66b3..ce8a0ea4b44bface72a1345df10c8a3133e95f01 100755 --- a/ai/BUILD.gn +++ b/ai/BUILD.gn @@ -24,6 +24,7 @@ group("ai") { "mindspore/mindsporectest:ActsMindSporeTest", "mindspore/mindsporejstest:ActsMindsporeJSTest", "mindspore/mindsporendktest:ActsMindSporeNdkTest", + "mindspore/ai_mindsporectest_20:ActsMindSporec20Test", "nnrtndk:ActsAInnrtNdkTest", ] } diff --git a/ai/mindspore/ai_mindsporectest_20/AppScope/app.json5 b/ai/mindspore/ai_mindsporectest_20/AppScope/app.json5 new file mode 100644 index 0000000000000000000000000000000000000000..fe74e3606b4aed118e5f95799084e82ade9b1183 --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/AppScope/app.json5 @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "app": { + "bundleName": "com.acts.mindsporectest20", + "vendor": "huawei", + "versionCode": 1000000, + "versionName": "1.0.0", + "icon": "$media:app_icon", + "label": "$string:app_name" + } +} diff --git a/ai/mindspore/ai_mindsporectest_20/AppScope/resources/base/element/string.json b/ai/mindspore/ai_mindsporectest_20/AppScope/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..1c817e563c65c66ee906ccd68eb178a75057bb3f --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/AppScope/resources/base/element/string.json @@ -0,0 +1,12 @@ +{ + "string": [ + { + "name": "app_name", + "value": "MindSporec20" + }, + { + "name": "description_application", + "value": "MindSporec20Test" + } + ] +} diff --git a/ai/mindspore/ai_mindsporectest_20/AppScope/resources/base/media/app_icon.png b/ai/mindspore/ai_mindsporectest_20/AppScope/resources/base/media/app_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/ai/mindspore/ai_mindsporectest_20/BUILD.gn b/ai/mindspore/ai_mindsporectest_20/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..5b53935781d0803dc128f438866f40a9cbcc7d77 --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/BUILD.gn @@ -0,0 +1,32 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//test/xts/tools/build/suite.gni") + +ohos_app_assist_suite("ActsMindSporec20MainTest") { + testonly = true + certificate_profile = "./signature/openharmony_sx.p7b" + hap_name = "ActsMindSporec20MainTest" + part_name = "mindspore" + subsystem_name = "ai" +} + +ohos_js_app_suite("ActsMindSporec20Test") { + test_hap = true + testonly = true + certificate_profile = "./signature/openharmony_sx.p7b" + hap_name = "ActsMindSporec20Test" + subsystem_name = "ai" + part_name = "mindspore" + deps = [ ":ActsMindSporec20MainTest" ] +} diff --git a/ai/mindspore/ai_mindsporectest_20/Test.json b/ai/mindspore/ai_mindsporectest_20/Test.json new file mode 100644 index 0000000000000000000000000000000000000000..1651449ba66650658460e8fe4b597b823645361b --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/Test.json @@ -0,0 +1,26 @@ +{ + "description": "Configuration for mindsporectest20 Tests", + "driver": { + "type": "OHJSUnitTest", + "test-timeout": "180000", + "bundle-name": "com.acts.mindsporectest20", + "module-name": "entry_test", + "shell-timeout": "600000", + "testcase-timeout": 60000 + }, + "kits": [{ + "test-file-name": [ + "ActsMindSporec20Test.hap", + "ActsMindSporec20MainTest.hap" + ], + "type": "AppInstallKit", + "cleanup-apps": true + }, { + "type": "ShellKit", + "run-command": [ + "power-shell wakeup", + "power-shell setmode 602" + ] + + }] +} diff --git a/ai/mindspore/ai_mindsporectest_20/build-profile.json5 b/ai/mindspore/ai_mindsporectest_20/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..c873ff9d8a3cfd37afb04434875dcfa98a2f37d9 --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/build-profile.json5 @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "app": { + "products": [ + { + "name": "default", + "signingConfig": "default", + "compileSdkVersion": 20, + "compatibleSdkVersion": 20, + "targetSdkVersion": 20, + "runtimeOS": "OpenHarmony" + } + ], + "signingConfigs": [ + + ] + }, + "modules": [ + { + "name": "entry", + "srcPath": "./entry", + "targets": [ + { + "name": "default", + "applyToProducts": [ + "default" + ] + } + ] + } + ] +} diff --git a/ai/mindspore/ai_mindsporectest_20/entry/build-profile.json5 b/ai/mindspore/ai_mindsporectest_20/entry/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..d00b6dcd409d04b0b56a81aee1fde98eacdd7edf --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/build-profile.json5 @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "apiType": 'stageMode', + "buildOption": { + "externalNativeOptions": { + "path": "./src/main/cpp/CMakeLists.txt", + "arguments": "", + "cppFlags": "", + "abiFilters": ["arm64-v8a", "x86_64", "armeabi-v7a"] + } + }, + "targets": [ + { + "name": "default", + }, + { + "name": "ohosTest", + } + ] +} diff --git a/ai/mindspore/ai_mindsporectest_20/entry/hvigorfile.ts b/ai/mindspore/ai_mindsporectest_20/entry/hvigorfile.ts new file mode 100644 index 0000000000000000000000000000000000000000..f9973af5eb59e35539012ef41c858ede21a4e1c9 --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/hvigorfile.ts @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently. +export { hapTasks } from '@ohos/hvigor-ohos-plugin'; diff --git a/ai/mindspore/ai_mindsporectest_20/entry/oh-package.json5 b/ai/mindspore/ai_mindsporectest_20/entry/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..c6d31b285bb4bb2391761b9950aa7c31cab74ed2 --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/oh-package.json5 @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +{ + "license": "", + "devDependencies": { + "@types/libmindsporendk.so": "file:./src/main/cpp/types/libmindsporendk" + }, + "author": "", + "name": "entry", + "description": "Please describe the basic information.", + "main": "", + "version": "1.0.0", + "dependencies": { + "@types/libmindsporendk.so": "file:./src/main/cpp/types/libmindsporendk" + } +} diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/main/cpp/CMakeLists.txt b/ai/mindspore/ai_mindsporectest_20/entry/src/main/cpp/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..69482ca72f72efcd2de345548281e00e412b35a1 --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/main/cpp/CMakeLists.txt @@ -0,0 +1,19 @@ +# the minimum version of CMake. +cmake_minimum_required(VERSION 3.5.0) +project(MindSporeNdk) + +set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) + +if(DEFINED PACKAGE_FIND_FILE) + include(${PACKAGE_FIND_FILE}) +endif() + +include_directories(${NATIVERENDER_ROOT_PATH} + ${NATIVERENDER_ROOT_PATH}/include) + +add_library(mindsporendk SHARED mindspore/NapiRenderInitTest.cpp +common/CommonTest.cpp +mindspore/MindSporeFormatTest.cpp +) + +target_link_libraries(mindsporendk PUBLIC libace_napi.z.so libhilog_ndk.z.so libmindspore_lite_ndk.so) \ No newline at end of file diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/main/cpp/common/Common.h b/ai/mindspore/ai_mindsporectest_20/entry/src/main/cpp/common/Common.h new file mode 100644 index 0000000000000000000000000000000000000000..c8dddd0ff1dfc69a46ec9a5de33c861423f4963c --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/main/cpp/common/Common.h @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_XCOMPONENT_COMMON_H +#define NATIVE_XCOMPONENT_COMMON_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define PARAM_0_POINT_5 0.5 +#define PARAM_1_POINT_5 1.5 +#define PARAM_0_POINT_6 0.6 +#define PARAM_1_POINT_1 1.1 +#define PARAM_NEGATIVE_0_POINT_1 (-0.1) +#define PARAM_NEGATIVE_0_POINT_8 (-0.8) +#define PARAM_0 0 +#define PARAM_1 1 +#define PARAM_2 2 +#define PARAM_3 3 +#define PARAM_4 4 +#define PARAM_5 5 +#define PARAM_6 6 +#define PARAM_7 7 +#define PARAM_8 8 +#define PARAM_9 9 +#define PARAM_10 10 +#define PARAM_10 10 +#define PARAM_11 11 +#define PARAM_12 12 +#define PARAM_13 13 +#define PARAM_14 14 +#define PARAM_15 15 +#define PARAM_16 16 +#define PARAM_17 17 +#define PARAM_18 18 +#define PARAM_19 19 +#define PARAM_20 20 +#define PARAM_21 21 +#define PARAM_30 30 +#define PARAM_33 33 +#define PARAM_50 50 +#define PARAM_80 80 +#define PARAM_50_POINT_5 50.5 +#define PARAM_80_POINT_5 80.5 +#define PARAM_101_POINT_5 101.5 +#define PARAM_90 90 +#define PARAM_96 96 +#define PARAM_100 100 +#define PARAM_101 101 +#define PARAM_200 200 +#define PARAM_255 255 +#define PARAM_500 500 +#define PARAM_501 501 +#define PARAM_1000 1000 +#define PARAM_1001 1001 +#define PARAM_3600 3600 +#define PARAM_10000 10000 +#define PARAM_4294967296 4294967296 +#define PARAM_NEGATIVE_1 (-1) +#define PARAM_NEGATIVE_2 (-2) +#define PARAM_NEGATIVE_9 (-9) +#define PARAM_NEGATIVE_10 (-10) +#define PARAM_NEGATIVE_30 (-30) +#define PARAM_NEGATIVE_50 (-50) +#define PARAM_NEGATIVE_50_POINT_5 (-50.5) +#define PARAM_NEGATIVE_100 (-100) +#define PARAM_64 64 +#define DEFAULT_MARGIN 10 +#define SIZE_2 2 +#define SIZE_3 3 +#define SIZE_5 5 +#define SIZE_10 10 +#define SIZE_20 20 +#define SIZE_30 30 +#define SIZE_40 40 +#define SIZE_50 50 +#define SIZE_56 56 +#define SIZE_60 60 +#define SIZE_70 70 +#define SIZE_80 80 +#define SIZE_90 90 +#define SIZE_100 100 +#define SIZE_110 110 +#define SIZE_120 120 +#define SIZE_180 180 +#define SIZE_150 150 +#define SIZE_200 200 +#define SIZE_250 250 +#define SIZE_300 300 +#define SIZE_350 350 +#define SIZE_400 400 +#define SIZE_500 500 +#define SIZE_600 600 +#define SIZE_10000 10000 +#define SUCCESS 0 +#define INVALID_PARAM 401 +#define NULL_PARAM 404 +#define COLOR_BLACK 0xFF000000 +#define COLOR_RED 0xFFFF0000 +#define COLOR_GREEN 0xFF00FF00 +#define COLOR_BLUE 0xFF0000FF +#define COLOR_YELLOW 0xFFFFFF00 +#define COLOR_PURPLE 0xFFFF11FF +#define COLOR_GRAY 0xFFDDDDDD +#define COLOR_CYAN 0xFF00FFFF +#define COLOR_WHITE 0xFFFFFFFF +#define COLOR_PINK 0xFFFFC0CB +#define COLOR_ILLEGAL 0x00000000 +#define ON_CLICK_EVENT_ID 6001 +#define ON_FOCUS_EVENT_ID 6002 +#define ON_TOUCH_EVENT_ID 6003 +#define ON_AREA_CHANGE_EVENT_ID 6004 +#define ON_APPEAR_EVENT_ID 6005 +#define ON_BLUR_EVENT_ID 6006 +#define ON_CHANGE_EVENT_ID 6007 +#define ON_SUBMIT_EVENT_ID 6008 +#define ON_CUT_EVENT_ID 6009 +#define ON_PASTE_EVENT_ID 6010 +#define ON_MEASURE_EVENT_ID 6011 +#define ON_LAYOUT_EVENT_ID 6012 +#define ON_DRAW_EVENT_ID 6013 +#define ON_CUSTOM_EVENT_1_ID 9001 +#define ON_CUSTOM_EVENT_2_ID 9002 +#define ON_CUSTOM_EVENT_3_ID 9003 +#define ON_CUSTOM_EVENT_4_ID 9004 +#define ON_CUSTOM_EVENT_5_ID 9005 +#define ON_CUSTOM_EVENT_6_ID 9006 +#define ON_CUSTOM_EVENT_11_ID 9011 +#define ON_CUSTOM_EVENT_12_ID 9012 +#define ON_CUSTOM_EVENT_13_ID 9013 +#define ON_CUSTOM_EVENT_14_ID 9014 +#define ON_CUSTOM_EVENT_15_ID 9015 +#define ON_CUSTOM_EVENT_16_ID 9016 +#define PARAM_NEGATIVE_1 (-1) +#define PARAM_NEGATIVE_100 (-100) +#define PARAM_NEGATIVE_5 (-5) +#define COLUMN_WIDTH_AND_HEIGHT 210 + +/** + * Log print domain. + */ +const unsigned int LOG_PRINT_DOMAIN = 0xFF00; + +napi_property_descriptor XL(char* functionName, napi_callback func); +#endif // NATIVE_XCOMPONENT_COMMON_H diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/main/cpp/common/CommonTest.cpp b/ai/mindspore/ai_mindsporectest_20/entry/src/main/cpp/common/CommonTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..05582365e809c6e74b252f81433a6a3def553439 --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/main/cpp/common/CommonTest.cpp @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "common/Common.h" + +napi_property_descriptor XL(char* functionName, napi_callback func) +{ + return { functionName, nullptr, func, nullptr, nullptr, nullptr, napi_default, nullptr }; +} diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/main/cpp/mindspore/MindSporeFormatTest.cpp b/ai/mindspore/ai_mindsporectest_20/entry/src/main/cpp/mindspore/MindSporeFormatTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ba9960555117ef34e1f78964089c71223d61a3d7 --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/main/cpp/mindspore/MindSporeFormatTest.cpp @@ -0,0 +1,245 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "MindSporeFormatTest.h" +#include +#include + +namespace MindSporeFormatTest { +napi_value FormatTest_001(napi_env env, napi_callback_info info) +{ + napi_value retValue; + constexpr size_t create_shape_num = 4; + int64_t create_shape[create_shape_num] = {1, 48, 48, 3}; + OH_AI_DataType datatype = OH_AI_DATATYPE_NUMBERTYPE_FLOAT32; + OH_AI_TensorHandle tensor = OH_AI_TensorCreate("data", datatype, create_shape, create_shape_num, nullptr, 0); + OH_AI_TensorSetFormat(tensor, OH_AI_FORMAT_NCHW); + auto ret = OH_AI_TensorGetFormat(tensor); + napi_create_int32(env, ret == OH_AI_FORMAT_NCHW ? 0 : 1, &retValue); + OH_AI_TensorDestroy(&tensor); + return retValue; +} + +napi_value FormatTest_002(napi_env env, napi_callback_info info) +{ + napi_value retValue; + constexpr size_t create_shape_num = 4; + int64_t create_shape[create_shape_num] = {1, 48, 48, 3}; + OH_AI_DataType datatype = OH_AI_DATATYPE_NUMBERTYPE_FLOAT32; + OH_AI_TensorHandle tensor = OH_AI_TensorCreate("data", datatype, create_shape, create_shape_num, nullptr, 0); + OH_AI_TensorSetFormat(tensor, OH_AI_FORMAT_NHWC4); + auto ret = OH_AI_TensorGetFormat(tensor); + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "datatype", "OH_AI_DATATYPE_UNKNOWN: %{public}d", ret); + napi_create_int32(env, ret == OH_AI_FORMAT_NHWC4 ? 0 : 1, &retValue); + OH_AI_TensorDestroy(&tensor); + return retValue; +} + +napi_value FormatTest_003(napi_env env, napi_callback_info info) +{ + napi_value retValue; + constexpr size_t create_shape_num = 4; + int64_t create_shape[create_shape_num] = {1, 48, 48, 3}; + OH_AI_DataType datatype = OH_AI_DATATYPE_NUMBERTYPE_FLOAT32; + OH_AI_TensorHandle tensor = OH_AI_TensorCreate("data", datatype, create_shape, create_shape_num, nullptr, 0); + OH_AI_TensorSetFormat(tensor, OH_AI_FORMAT_HWCK); + auto ret = OH_AI_TensorGetFormat(tensor); + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "datatype", "OH_AI_DATATYPE_UNKNOWN: %{public}d", ret); + napi_create_int32(env, ret == OH_AI_FORMAT_HWCK ? 0 : 1, &retValue); + OH_AI_TensorDestroy(&tensor); + return retValue; +} + +napi_value FormatTest_004(napi_env env, napi_callback_info info) +{ + napi_value retValue; + constexpr size_t create_shape_num = 4; + int64_t create_shape[create_shape_num] = {1, 48, 48, 3}; + OH_AI_DataType datatype = OH_AI_DATATYPE_NUMBERTYPE_FLOAT32; + OH_AI_TensorHandle tensor = OH_AI_TensorCreate("data", datatype, create_shape, create_shape_num, nullptr, 0); + OH_AI_TensorSetFormat(tensor, OH_AI_FORMAT_KCHW); + auto ret = OH_AI_TensorGetFormat(tensor); + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "datatype", "OH_AI_DATATYPE_UNKNOWN: %{public}d", ret); + napi_create_int32(env, ret == OH_AI_FORMAT_KCHW ? 0 : 1, &retValue); + OH_AI_TensorDestroy(&tensor); + return retValue; +} + +napi_value FormatTest_005(napi_env env, napi_callback_info info) +{ + napi_value retValue; + constexpr size_t create_shape_num = 4; + int64_t create_shape[create_shape_num] = {1, 48, 48, 3}; + OH_AI_DataType datatype = OH_AI_DATATYPE_NUMBERTYPE_FLOAT32; + OH_AI_TensorHandle tensor = OH_AI_TensorCreate("data", datatype, create_shape, create_shape_num, nullptr, 0); + OH_AI_TensorSetFormat(tensor, OH_AI_FORMAT_CKHW); + auto ret = OH_AI_TensorGetFormat(tensor); + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "datatype", "OH_AI_DATATYPE_UNKNOWN: %{public}d", ret); + napi_create_int32(env, ret == OH_AI_FORMAT_CKHW ? 0 : 1, &retValue); + OH_AI_TensorDestroy(&tensor); + return retValue; +} + +napi_value FormatTest_006(napi_env env, napi_callback_info info) +{ + napi_value retValue; + constexpr size_t create_shape_num = 4; + int64_t create_shape[create_shape_num] = {1, 48, 48, 3}; + OH_AI_DataType datatype = OH_AI_DATATYPE_NUMBERTYPE_FLOAT32; + OH_AI_TensorHandle tensor = OH_AI_TensorCreate("data", datatype, create_shape, create_shape_num, nullptr, 0); + OH_AI_TensorSetFormat(tensor, OH_AI_FORMAT_KHWC); + auto ret = OH_AI_TensorGetFormat(tensor); + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "datatype", "OH_AI_DATATYPE_UNKNOWN: %{public}d", ret); + napi_create_int32(env, ret == OH_AI_FORMAT_KHWC ? 0 : 1, &retValue); + OH_AI_TensorDestroy(&tensor); + return retValue; +} + +napi_value FormatTest_007(napi_env env, napi_callback_info info) +{ + napi_value retValue; + constexpr size_t create_shape_num = 4; + int64_t create_shape[create_shape_num] = {1, 48, 48, 3}; + OH_AI_DataType datatype = OH_AI_DATATYPE_NUMBERTYPE_FLOAT32; + OH_AI_TensorHandle tensor = OH_AI_TensorCreate("data", datatype, create_shape, create_shape_num, nullptr, 0); + OH_AI_TensorSetFormat(tensor, OH_AI_FORMAT_CHWK); + auto ret = OH_AI_TensorGetFormat(tensor); + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "datatype", "OH_AI_DATATYPE_UNKNOWN: %{public}d", ret); + napi_create_int32(env, ret == OH_AI_FORMAT_CHWK ? 0 : 1, &retValue); + OH_AI_TensorDestroy(&tensor); + return retValue; +} + +napi_value FormatTest_008(napi_env env, napi_callback_info info) +{ + napi_value retValue; + constexpr size_t create_shape_num = 4; + int64_t create_shape[create_shape_num] = {1, 48, 48, 3}; + OH_AI_DataType datatype = OH_AI_DATATYPE_NUMBERTYPE_FLOAT32; + OH_AI_TensorHandle tensor = OH_AI_TensorCreate("data", datatype, create_shape, create_shape_num, nullptr, 0); + OH_AI_TensorSetFormat(tensor, OH_AI_FORMAT_HW); + auto ret = OH_AI_TensorGetFormat(tensor); + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "datatype", "OH_AI_DATATYPE_UNKNOWN: %{public}d", ret); + napi_create_int32(env, ret == OH_AI_FORMAT_HW ? 0 : 1, &retValue); + OH_AI_TensorDestroy(&tensor); + return retValue; +} + +napi_value FormatTest_009(napi_env env, napi_callback_info info) +{ + napi_value retValue; + constexpr size_t create_shape_num = 4; + int64_t create_shape[create_shape_num] = {1, 48, 48, 3}; + OH_AI_DataType datatype = OH_AI_DATATYPE_NUMBERTYPE_FLOAT32; + OH_AI_TensorHandle tensor = OH_AI_TensorCreate("data", datatype, create_shape, create_shape_num, nullptr, 0); + OH_AI_TensorSetFormat(tensor, OH_AI_FORMAT_HW4); + auto ret = OH_AI_TensorGetFormat(tensor); + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "datatype", "OH_AI_DATATYPE_UNKNOWN: %{public}d", ret); + napi_create_int32(env, ret == OH_AI_FORMAT_HW4 ? 0 : 1, &retValue); + OH_AI_TensorDestroy(&tensor); + return retValue; +} + +napi_value FormatTest_010(napi_env env, napi_callback_info info) +{ + napi_value retValue; + constexpr size_t create_shape_num = 4; + int64_t create_shape[create_shape_num] = {1, 48, 48, 3}; + OH_AI_DataType datatype = OH_AI_DATATYPE_NUMBERTYPE_FLOAT32; + OH_AI_TensorHandle tensor = OH_AI_TensorCreate("data", datatype, create_shape, create_shape_num, nullptr, 0); + OH_AI_TensorSetFormat(tensor, OH_AI_FORMAT_NC); + auto ret = OH_AI_TensorGetFormat(tensor); + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "datatype", "OH_AI_DATATYPE_UNKNOWN: %{public}d", ret); + napi_create_int32(env, ret == OH_AI_FORMAT_NC ? 0 : 1, &retValue); + OH_AI_TensorDestroy(&tensor); + return retValue; +} + +napi_value FormatTest_011(napi_env env, napi_callback_info info) +{ + napi_value retValue; + constexpr size_t create_shape_num = 4; + int64_t create_shape[create_shape_num] = {1, 48, 48, 3}; + OH_AI_DataType datatype = OH_AI_DATATYPE_NUMBERTYPE_FLOAT32; + OH_AI_TensorHandle tensor = OH_AI_TensorCreate("data", datatype, create_shape, create_shape_num, nullptr, 0); + OH_AI_TensorSetFormat(tensor, OH_AI_FORMAT_NC4); + auto ret = OH_AI_TensorGetFormat(tensor); + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "datatype", "OH_AI_DATATYPE_UNKNOWN: %{public}d", ret); + napi_create_int32(env, ret == OH_AI_FORMAT_NC4 ? 0 : 1, &retValue); + OH_AI_TensorDestroy(&tensor); + return retValue; +} + +napi_value FormatTest_012(napi_env env, napi_callback_info info) +{ + napi_value retValue; + constexpr size_t create_shape_num = 4; + int64_t create_shape[create_shape_num] = {1, 48, 48, 3}; + OH_AI_DataType datatype = OH_AI_DATATYPE_NUMBERTYPE_FLOAT32; + OH_AI_TensorHandle tensor = OH_AI_TensorCreate("data", datatype, create_shape, create_shape_num, nullptr, 0); + OH_AI_TensorSetFormat(tensor, OH_AI_FORMAT_NC4HW4); + auto ret = OH_AI_TensorGetFormat(tensor); + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "datatype", "OH_AI_DATATYPE_UNKNOWN: %{public}d", ret); + napi_create_int32(env, ret == OH_AI_FORMAT_NC4HW4 ? 0 : 1, &retValue); + OH_AI_TensorDestroy(&tensor); + return retValue; +} + +napi_value FormatTest_013(napi_env env, napi_callback_info info) +{ + napi_value retValue; + constexpr size_t create_shape_num = 4; + int64_t create_shape[create_shape_num] = {1, 48, 48, 3}; + OH_AI_DataType datatype = OH_AI_DATATYPE_NUMBERTYPE_FLOAT32; + OH_AI_TensorHandle tensor = OH_AI_TensorCreate("data", datatype, create_shape, create_shape_num, nullptr, 0); + OH_AI_TensorSetFormat(tensor, OH_AI_FORMAT_NCDHW); + auto ret = OH_AI_TensorGetFormat(tensor); + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "datatype", "OH_AI_DATATYPE_UNKNOWN: %{public}d", ret); + napi_create_int32(env, ret == OH_AI_FORMAT_NCDHW ? 0 : 1, &retValue); + OH_AI_TensorDestroy(&tensor); + return retValue; +} + +napi_value FormatTest_014(napi_env env, napi_callback_info info) +{ + napi_value retValue; + constexpr size_t create_shape_num = 4; + int64_t create_shape[create_shape_num] = {1, 48, 48, 3}; + OH_AI_DataType datatype = OH_AI_DATATYPE_NUMBERTYPE_FLOAT32; + OH_AI_TensorHandle tensor = OH_AI_TensorCreate("data", datatype, create_shape, create_shape_num, nullptr, 0); + OH_AI_TensorSetFormat(tensor, OH_AI_FORMAT_NWC); + auto ret = OH_AI_TensorGetFormat(tensor); + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "datatype", "OH_AI_DATATYPE_UNKNOWN: %{public}d", ret); + napi_create_int32(env, ret == OH_AI_FORMAT_NWC ? 0 : 1, &retValue); + OH_AI_TensorDestroy(&tensor); + return retValue; +} + +napi_value FormatTest_015(napi_env env, napi_callback_info info) +{ + napi_value retValue; + constexpr size_t create_shape_num = 4; + int64_t create_shape[create_shape_num] = {1, 48, 48, 3}; + OH_AI_DataType datatype = OH_AI_DATATYPE_NUMBERTYPE_FLOAT32; + OH_AI_TensorHandle tensor = OH_AI_TensorCreate("data", datatype, create_shape, create_shape_num, nullptr, 0); + OH_AI_TensorSetFormat(tensor, OH_AI_FORMAT_NCW); + auto ret = OH_AI_TensorGetFormat(tensor); + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "datatype", "OH_AI_DATATYPE_UNKNOWN: %{public}d", ret); + napi_create_int32(env, ret == OH_AI_FORMAT_NCW? 0 : 1, &retValue); + OH_AI_TensorDestroy(&tensor); + return retValue; +} + +} \ No newline at end of file diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/main/cpp/mindspore/MindSporeFormatTest.h b/ai/mindspore/ai_mindsporectest_20/entry/src/main/cpp/mindspore/MindSporeFormatTest.h new file mode 100644 index 0000000000000000000000000000000000000000..3f4a8a6f1128ee4545e63fe9e3436f2c59988ada --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/main/cpp/mindspore/MindSporeFormatTest.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef MINDSPORE_FORMAT_TEST_H +#define MINDSPORE_FORMAT_TEST_H + +#include +#include "common/Common.h" + +namespace MindSporeFormatTest { + napi_value FormatTest_001(napi_env env, napi_callback_info info); + napi_value FormatTest_002(napi_env env, napi_callback_info info); + napi_value FormatTest_003(napi_env env, napi_callback_info info); + napi_value FormatTest_004(napi_env env, napi_callback_info info); + napi_value FormatTest_005(napi_env env, napi_callback_info info); + napi_value FormatTest_006(napi_env env, napi_callback_info info); + napi_value FormatTest_007(napi_env env, napi_callback_info info); + napi_value FormatTest_008(napi_env env, napi_callback_info info); + napi_value FormatTest_009(napi_env env, napi_callback_info info); + napi_value FormatTest_010(napi_env env, napi_callback_info info); + napi_value FormatTest_011(napi_env env, napi_callback_info info); + napi_value FormatTest_012(napi_env env, napi_callback_info info); + napi_value FormatTest_013(napi_env env, napi_callback_info info); + napi_value FormatTest_014(napi_env env, napi_callback_info info); + napi_value FormatTest_015(napi_env env, napi_callback_info info); + +} + +#endif // MINDSPORE_FORMAT_TEST_H \ No newline at end of file diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/main/cpp/mindspore/NapiRenderInitTest.cpp b/ai/mindspore/ai_mindsporectest_20/entry/src/main/cpp/mindspore/NapiRenderInitTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..412022a3152ab6770b15c8e6d63c9dcb0a3b8c5a --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/main/cpp/mindspore/NapiRenderInitTest.cpp @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "common/Common.h" +#include "mindspore/MindSporeFormatTest.h" + +namespace MindSporeTest { +EXTERN_C_START +static void RenderInitPush0(napi_property_descriptor* desc) +{ + napi_property_descriptor descTemp[] = { + {"FormatTest_001", nullptr, MindSporeFormatTest::FormatTest_001, + nullptr, nullptr, nullptr, napi_default, nullptr}, + {"FormatTest_002", nullptr, MindSporeFormatTest::FormatTest_002, + nullptr, nullptr, nullptr, napi_default, nullptr}, + {"FormatTest_003", nullptr, MindSporeFormatTest::FormatTest_003, + nullptr, nullptr, nullptr, napi_default, nullptr}, + {"FormatTest_004", nullptr, MindSporeFormatTest::FormatTest_004, + nullptr, nullptr, nullptr, napi_default, nullptr}, + {"FormatTest_005", nullptr, MindSporeFormatTest::FormatTest_005, + nullptr, nullptr, nullptr, napi_default, nullptr}, + {"FormatTest_006", nullptr, MindSporeFormatTest::FormatTest_006, + nullptr, nullptr, nullptr, napi_default, nullptr}, + {"FormatTest_007", nullptr, MindSporeFormatTest::FormatTest_007, + nullptr, nullptr, nullptr, napi_default, nullptr}, + {"FormatTest_008", nullptr, MindSporeFormatTest::FormatTest_008, + nullptr, nullptr, nullptr, napi_default, nullptr}, + {"FormatTest_009", nullptr, MindSporeFormatTest::FormatTest_009, + nullptr, nullptr, nullptr, napi_default, nullptr}, + {"FormatTest_010", nullptr, MindSporeFormatTest::FormatTest_010, + nullptr, nullptr, nullptr, napi_default, nullptr}, + {"FormatTest_011", nullptr, MindSporeFormatTest::FormatTest_011, + nullptr, nullptr, nullptr, napi_default, nullptr}, + {"FormatTest_012", nullptr, MindSporeFormatTest::FormatTest_012, + nullptr, nullptr, nullptr, napi_default, nullptr}, + {"FormatTest_013", nullptr, MindSporeFormatTest::FormatTest_013, + nullptr, nullptr, nullptr, napi_default, nullptr}, + {"FormatTest_014", nullptr, MindSporeFormatTest::FormatTest_014, + nullptr, nullptr, nullptr, napi_default, nullptr}, + {"FormatTest_015", nullptr, MindSporeFormatTest::FormatTest_015, + nullptr, nullptr, nullptr, napi_default, nullptr}, + }; + for (size_t index = 0; index < sizeof(descTemp) / sizeof(descTemp[0]); index++) { + desc[index] = descTemp[index]; + } +} + +static napi_value RenderInit(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[100] = {}; + RenderInitPush0(desc); + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + return exports; +} +EXTERN_C_END + +static napi_module mindsporendkModule = {.nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = RenderInit, + .nm_modname = "mindsporendk", + .nm_priv = ((void *)0), + .reserved = {0}}; + +extern "C" __attribute__((constructor)) void RegisterModule(void) { napi_module_register(&mindsporendkModule); } +} \ No newline at end of file diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/main/cpp/types/libmindsporendk/Index.d.ts b/ai/mindspore/ai_mindsporectest_20/entry/src/main/cpp/types/libmindsporendk/Index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..92f6b810bfe6e301ded8cb03497b12d3c009d037 --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/main/cpp/types/libmindsporendk/Index.d.ts @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const FormatTest_001: () => number; +export const FormatTest_002: () => number; +export const FormatTest_003: () => number; +export const FormatTest_004: () => number; +export const FormatTest_005: () => number; +export const FormatTest_006: () => number; +export const FormatTest_007: () => number; +export const FormatTest_008: () => number; +export const FormatTest_009: () => number; +export const FormatTest_010: () => number; +export const FormatTest_011: () => number; +export const FormatTest_012: () => number; +export const FormatTest_013: () => number; +export const FormatTest_014: () => number; +export const FormatTest_015: () => number; \ No newline at end of file diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/main/cpp/types/libmindsporendk/oh-package.json5 b/ai/mindspore/ai_mindsporectest_20/entry/src/main/cpp/types/libmindsporendk/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..429de443d36ab4531f48b57cc96564211233593b --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/main/cpp/types/libmindsporendk/oh-package.json5 @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +{ + "name": "libmindsporendk.so", + "types": "./Index.d.ts", + "version": "1.0.0", + "description": "Function list of mindsporendk capi." +} diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/main/ets/entryability/EntryAbility.ets b/ai/mindspore/ai_mindsporectest_20/entry/src/main/ets/entryability/EntryAbility.ets new file mode 100644 index 0000000000000000000000000000000000000000..4afe5ede4869c94720c4646fed76a3e966b59efd --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/main/ets/entryability/EntryAbility.ets @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import UIAbility from '@ohos.app.ability.UIAbility'; +import hilog from '@ohos.hilog'; +import window from '@ohos.window'; +import { AbilityConstant, Want } from '@kit.AbilityKit'; + +export default class EntryAbility extends UIAbility { + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); + } + + onDestroy() { + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy'); + } + + onWindowStageCreate(windowStage: window.WindowStage) { + // Main window is created, set main page for this ability + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); + + windowStage.loadContent('pages/Index', (err, data) => { + if (err.code) { + hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); + return; + } + hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); + }); + } + + onWindowStageDestroy() { + // Main window is destroyed, release UI related resources + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy'); + } + + onForeground() { + // Ability has brought to foreground + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground'); + } + + onBackground() { + // Ability has back to background + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground'); + } +}; diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/main/ets/pages/Index.ets b/ai/mindspore/ai_mindsporectest_20/entry/src/main/ets/pages/Index.ets new file mode 100644 index 0000000000000000000000000000000000000000..e50e17b7070252e8b4723fc21ac6ebdc7177ccb9 --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/main/ets/pages/Index.ets @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { NodeContent, router } from '@kit.ArkUI'; + +@Entry +@Component +struct NodeUtilsTest { + private nodeContent: NodeContent = new NodeContent(); + + build() { + Column() { + Button('111') + .onClick(()=>{ + + }) + } + .width('100%') + .height('100%') + } +} \ No newline at end of file diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/main/module.json5 b/ai/mindspore/ai_mindsporectest_20/entry/src/main/module.json5 new file mode 100644 index 0000000000000000000000000000000000000000..53fc6adf3b95c74d661c946251101c5bf3e50e4f --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/main/module.json5 @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "module": { + "name": "entry", + "type": "entry", + "description": "$string:module_desc", + "mainElement": "MainAbility", + "deviceTypes": [], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:main_pages", + "abilities": [ + { + "name": "EntryAbility", + "srcEntry": "./ets/entryability/EntryAbility.ets", + "description": "$string:EntryAbility_desc", + "icon": "$media:icon", + "label": "$string:EntryAbility_label", + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:start_window_background", + "exported": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "ohos.want.action.home" + ] + } + ] + } + ] + } +} \ No newline at end of file diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/main/resources/base/element/color.json b/ai/mindspore/ai_mindsporectest_20/entry/src/main/resources/base/element/color.json new file mode 100644 index 0000000000000000000000000000000000000000..3c712962da3c2751c2b9ddb53559afcbd2b54a02 --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/main/resources/base/element/color.json @@ -0,0 +1,8 @@ +{ + "color": [ + { + "name": "start_window_background", + "value": "#FFFFFF" + } + ] +} \ No newline at end of file diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/main/resources/base/element/string.json b/ai/mindspore/ai_mindsporectest_20/entry/src/main/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..632fa57802a5415b28a25dcff49ae0b39468571c --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/main/resources/base/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "XTSArkUINativeAPI20" + } + ] +} \ No newline at end of file diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/main/resources/base/media/icon.png b/ai/mindspore/ai_mindsporectest_20/entry/src/main/resources/base/media/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/main/resources/base/profile/main_pages.json b/ai/mindspore/ai_mindsporectest_20/entry/src/main/resources/base/profile/main_pages.json new file mode 100644 index 0000000000000000000000000000000000000000..1898d94f58d6128ab712be2c68acc7c98e9ab9ce --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/main/resources/base/profile/main_pages.json @@ -0,0 +1,5 @@ +{ + "src": [ + "pages/Index" + ] +} diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/main/resources/en_US/element/string.json b/ai/mindspore/ai_mindsporectest_20/entry/src/main/resources/en_US/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..632fa57802a5415b28a25dcff49ae0b39468571c --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/main/resources/en_US/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "XTSArkUINativeAPI20" + } + ] +} \ No newline at end of file diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/main/resources/zh_CN/element/string.json b/ai/mindspore/ai_mindsporectest_20/entry/src/main/resources/zh_CN/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..7a5f9194ba319b90a5b225c2ebb8a467166c5c30 --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/main/resources/zh_CN/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "模块描述" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "XTSArkUINativeAPI20" + } + ] +} \ No newline at end of file diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/main/syscap.json b/ai/mindspore/ai_mindsporectest_20/entry/src/main/syscap.json new file mode 100644 index 0000000000000000000000000000000000000000..d05ea9d7d5152602692ab3fc23d5fba0590adff3 --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/main/syscap.json @@ -0,0 +1,14 @@ +{ + "devices": { + "general": [], + "custom": [ + { + "xts": [ + "SystemCapability.Account.OsAccount", + "SystemCapability.Security.AccessToken", + "SystemCapability.Ai.MindSpore" + ] + } + ] + } +} \ No newline at end of file diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/Application/AbilityStage.ts b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/Application/AbilityStage.ts new file mode 100644 index 0000000000000000000000000000000000000000..54ee3310a3bb6780e4e9562b3c3b3ced1663a142 --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/Application/AbilityStage.ts @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import AbilityStage from '@ohos.app.ability.AbilityStage'; + +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log('[Demo] MyAbilityStage onCreate'); + globalThis.stageOnCreateRun = 1; + globalThis.stageContext = this.context; + } +} diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/MainAbility/MainAbility.ts b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/MainAbility/MainAbility.ts new file mode 100644 index 0000000000000000000000000000000000000000..32d00a6188c0752c15ee9dc7b1c9fd887228af0e --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/MainAbility/MainAbility.ts @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Ability from '@ohos.app.ability.UIAbility'; +import { hilog } from '@kit.PerformanceAnalysisKit'; +import { window } from '@kit.ArkUI'; +import { BusinessError } from '@ohos.base'; + +const TAG: string = '[createWindow]' + +export default class MainAbility extends Ability { + onCreate(want, launchParam) { + // Ability is creating, initialize resources for this ability + console.log(`${TAG} MainAbility onCreate`); + globalThis.abilityWant = want; + globalThis.abilityLaunchParam = launchParam; + } + + onDestroy() { + // Ability is destroying, release resources for this ability + console.log(`${TAG} MainAbility onDestroy`); + } + + onWindowStageCreate(windowStage) { + // Main window is created, set main page for this ability + console.log(`${TAG} MainAbility onWindowStageCreate windowStage=` + windowStage); + globalThis.windowStage = windowStage; + globalThis.context = this.context; + windowStage.setUIContent(this.context, 'MainAbility/pages/XTSIndex', null); + let windowClass: window.Window | undefined = undefined; + windowStage.getMainWindow((err: BusinessError, data) => { + let errCode: number = err.code; + if (errCode) { + console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err)); + return; + } + windowClass = data; + hilog.info(0x0000, 'testTag', 'Succeeded in obtaining the main window. Data: ' + JSON.stringify(data)); + try { + let properties : window.WindowProperties = windowClass.getWindowProperties(); + let wRect : window.Rect = properties.windowRect; + globalThis.winLeft = wRect.left; + globalThis.winTop = wRect.top; + hilog.info(0x0000, 'testTag', 'Succeeded get winLeft:' + globalThis.winLeft + ',winTop:' + globalThis.winTop ); + } catch (exception) { + hilog.error(0x0000, 'testTag', 'Failed to obtain the window properties. Cause: ' + JSON.stringify(exception)); + } + }) + } + + onWindowStageDestroy() { + //Main window is destroyed, release UI related resources + console.log(`${TAG} MainAbility onWindowStageDestroy`); + } + + onForeground() { + // Ability has brought to foreground + console.log(`${TAG} MainAbility onForeground`); + } + + onBackground() { + // Ability has back to background + console.log(`${TAG} MainAbility onBackground`); + } +}; \ No newline at end of file diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/MainAbility/pages/XTSIndex.ets b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/MainAbility/pages/XTSIndex.ets new file mode 100644 index 0000000000000000000000000000000000000000..ccae742d96c407eba51a43fcd190cb15410fafe6 --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/MainAbility/pages/XTSIndex.ets @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; +import { Hypium } from '@ohos/hypium'; +import testsuite from '../../test/List.test'; +import { router } from '@kit.ArkUI'; + +@Entry +@Component +struct XTSIndex { + aboutToAppear() { + let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator() + let abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments() + console.info('start run testcase!!!') + Hypium.hypiumTest(abilityDelegator, abilityDelegatorArguments, testsuite) + } + + onPageShow(): void { + router.clear(); + } + + build() { + Flex({ + direction: FlexDirection.Column, + alignItems: ItemAlign.Center, + justifyContent: FlexAlign.Center + }) { + Text('ARKUI CAPI XTS') + .fontSize(36) + .fontWeight(FontWeight.Bold) + } + .width('100%') + .height('100%') + } +} diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/test/List.test.ets b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/test/List.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..9919c24b8cba97a6988f3ab1da17dff8e3af9cd7 --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/test/List.test.ets @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import MindSporeFormatTest from './mindsporetest/MindSporeFormatTest.test' + +export default function testsuite() { + MindSporeFormatTest() +} diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/test/common/Interfaces.d.ts b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/test/common/Interfaces.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7d33524ebc95d0f6e9c48a6f421b5f121dc9f94f --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/test/common/Interfaces.d.ts @@ -0,0 +1,216 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export class ComponentInfo { + $type: string; + $rect: Object[]; + $attrs: ComponentAttrs; +} + +export class ComponentAttrs { + backgroundColor: string; + switchPointColor: string; + enabled: string; + focusable: boolean; + trackColor: string; + checked: boolean; +} + +/** + * { + "$type": "Image", + "$ID": 17, + "$rect": "[288.00, 597.00],[432.00,741.00]", + "$debugLine": "", + "$attrs": { + "borderStyle": "BorderStyle.Solid", + "borderColor": "#FF000000", + "borderWidth": "0.00vp", + "borderRadius": { + "topLeft": "0.00vp", + "topRight": "0.00vp", + "bottomLeft": "0.00vp", + "bottomRight": "0.00vp" + }, + "border": "{\"style\":\"BorderStyle.Solid\",\"color\":\"#FF000000\",\"width\":\"0.00vp\",\"radius\":{\"topLeft\":\"0.00vp\",\"topRight\":\"0.00vp\",\"bottomLeft\":\"0.00vp\",\"bottomRight\":\"0.00vp\"}}", + "outlineStyle": "OutlineStyle.SOLID", + "outlineColor": "#FF000000", + "outlineWidth": "0.00vp", + "outlineRadius": { + "topLeft": "0.00vp", + "topRight": "0.00vp", + "bottomLeft": "0.00vp", + "bottomRight": "0.00vp" + }, + "outline": "{\"style\":\"OutlineStyle.SOLID\",\"color\":\"#FF000000\",\"width\":\"0.00vp\",\"radius\":{\"topLeft\":\"0.00vp\",\"topRight\":\"0.00vp\",\"bottomLeft\":\"0.00vp\",\"bottomRight\":\"0.00vp\"}}", + "pointLight": { + "lightIntensity": 0 + }, + "LightPosition": {}, + "borderImage": "{\"source\":\"\",\"slice\":\"0.00px\",\"width\":\"0.00px\",\"outset\":\"0.00px\",\"repeat\":\"RepeatMode.Stretch\",\"fill\":\"false\"}", + "overlay": { + "title": "", + "options": { + "align": "Alignment.Center", + "offset": { + "x": "0.00px", + "y": "0.00px" + } + } + }, + "position": { + "x": "", + "y": "" + }, + "offset": { + "x": "", + "y": "" + }, + "markAnchor": { + "x": "", + "y": "" + }, + "backgroundImage": "NONE", + "backgroundImageSize": "ImageSize.Auto", + "backgroundImagePosition": { + "x": 0, + "y": 0 + }, + "backdropBlur": 0, + "blur": 0, + "grayscale": 0, + "brightness": 1, + "saturate": 1, + "contrast": 1, + "sepia": 0, + "hueRotate": 0, + "colorBlend": "", + "blendMode": 0, + "shadow": { + "radius": "0.000000", + "color": "#FF000000", + "offsetX": "0.000000", + "offsetY": "0.000000", + "type": "0", + "fill": "0" + }, + "linearGradient": {}, + "sweepGradient": {}, + "radialGradient": {}, + "rotate": {}, + "scale": {}, + "translate": {}, + "clip": "false", + "mask": {}, + "backgroundBlurStyle": { + "value": "BlurStyle.NONE", + "options": { + "colorMode": "ThemeColorMode.System", + "adaptiveColor": "AdaptiveColor.Default", + "scale": 1 + } + }, + "backgroundEffect": { + "options": { + "radius": 0, + "saturation": 1, + "brightness": 1, + "color": "#00000000", + "adaptiveColor": "AdaptiveColor.Default", + "blurOption": "[0,0]" + } + }, + "transform": {}, + "backgroundColor": "#FF00FF00", + "zIndex": 0, + "opacity": 1, + "lightUpEffect": 0, + "sphericalEffect": 0, + "pixelStretchEffect": { + "left": "0.00px", + "right": "0.00px", + "top": "0.00px", + "bottom": "0.00px" + }, + "foregroundColor": "#00000001", + "obscured": [], + "renderGroup": "false", + "renderFit": "RenderFit.TOP_LEFT", + "useShadowBatching": "false", + "scrollable": false, + "width": "100.00vp", + "height": "100.00vp", + "size": { + "width": "100.00vp", + "height": "100.00vp" + }, + "constraintSize": "{\"minWidth\":\"0.00vp\",\"minHeight\":\"0.00vp\",\"maxWidth\":\"Infinityvp\",\"maxHeight\":\"Infinityvp\"}", + "align": "Alignment.Center", + "layoutWeight": 0, + "aspectRatio": "", + "flexBasis": "auto", + "flexGrow": 0, + "flexShrink": 1, + "alignSelf": "ItemAlign.Auto", + "displayPriority": 1, + "gridSpan": 1, + "gridOffset": 0, + "useSizeType": { + "default": { + "span": 1, + "offset": 0 + } + }, + "padding": "0.00vp", + "margin": "0.00vp", + "visibility": "Visibility.Visible", + "direction": "Direction.Auto", + "pixelRound": "{\"start\":\"PixelRoundCalcPolicy.NO_FORCE_ROUND\",\"top\":\"PixelRoundCalcPolicy.NO_FORCE_ROUND\",\"end\":\"PixelRoundCalcPolicy.NO_FORCE_ROUND\",\"bottom\":\"PixelRoundCalcPolicy.NO_FORCE_ROUND\"}", + "alt": "", + "objectFit": "ImageFit.Cover", + "verticalAlign": "VerticalAlign.BOTTOM", + "src": "", + "rawSrc": "", + "moduleName": "", + "sourceSize": "[0.00 x 0.00]", + "fitOriginalSize": "false", + "autoResize": "true", + "objectRepeat": "ImageRepeat.NoRepeat", + "interpolation": "ImageInterpolation.None", + "renderMode": "ImageRenderMode.Original", + "matchTextDirection": "false", + "fillColor": "#FF000000", + "colorFilter": "", + "copyOption": "CopyOptions.None", + "syncLoad": "false", + "draggable": "false", + "enableAnalyzer": "false", + "enabled": true, + "focusable": false, + "focused": false, + "defaultFocus": false, + "groupDefaultFocus": false, + "focusOnTouch": false, + "tabIndex": 0, + "hoverEffect": "HoverEffect.Auto", + "touchable": true, + "hitTestBehavior": "HitTestMode.Default", + "monopolizeEvents": false, + "responseRegion": [], + "mouseResponseRegion": [], + "id": "OnClickTestImage" + } + } + */ \ No newline at end of file diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/test/common/Rect.ets b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/test/common/Rect.ets new file mode 100644 index 0000000000000000000000000000000000000000..9b9463187f323793a533cd18d74969a0509bc738 --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/test/common/Rect.ets @@ -0,0 +1,21 @@ +/** + * Copyright (c) 2025 iSoftStone Information Technology (Group) Co.,Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default class RectValue { + left: number = 0; + top: number = 0; + right: number = 0; + bottom: number = 0; +} \ No newline at end of file diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/test/common/Utils.ets b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/test/common/Utils.ets new file mode 100644 index 0000000000000000000000000000000000000000..ca8b5d5ca64afcc451fc187fe34b0e5003b71de4 --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/test/common/Utils.ets @@ -0,0 +1,426 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import events_emitter from '@ohos.events.emitter'; +import { Driver, ON, PointerMatrix, Rect } from '@ohos.UiTest'; +import { ComponentInfo } from './Interfaces'; +import systemDateTime from '@ohos.systemDateTime'; +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry' +import fs from '@ohos.file.fs'; +import router from '@ohos.router'; +import RectValue from './Rect'; +import { expect, it } from '@ohos/hypium'; + +const KEY_CODE_EVENT_OK = 1; +const KEY_CODE_EVENT_ERROR = 0; + +export default class Utils { + static rect_left: number; + static rect_top: number; + static rect_right: number; + static rect_bottom: number; + static rect_value: RectValue; + static driver: Driver = Driver.create(); + + static sleep(time: number) { + return new Promise((resolve, reject) => { + setTimeout(() => { + resolve("ok") + }, time) + }).then(() => { + console.info(`sleep ${time} over...`) + }) + } + + static getSystemTime() { + return systemDateTime.getTime(true) / 1000 + } + + static getSandboxFileDir() { + let sandboxFileDir = AbilityDelegatorRegistry.getAbilityDelegator().getAppContext().filesDir + "/" + console.log(`[getSandboxFileDir] return ${sandboxFileDir}`); + return sandboxFileDir; + } + + static deleteFile(filePath: string) { + console.info("[deleteFile] filePath:" + filePath); + try { + fs.unlinkSync(filePath) + } catch (error) { + console.info("[deleteFile] error:" + error); + } + } + + static isFileExist(filePath: string): boolean { + console.info("[isFileExist] filePath:" + filePath); + try { + let fileExist = fs.accessSync(filePath) + console.info("[isFileExist] return:" + fileExist); + return fileExist + } catch (error) { + console.info("[isFileExist] error:" + error); + return false + } + } + + static async flingComponent(key: string, isHorizontal: boolean, isForward: boolean) { + let driver = Driver.create(); + let rect = Utils.getComponentRect(key); + let centerX = Math.round(globalThis.winLeft + Utils.getRectHorizontalCenterX(rect)) + let centerY = Math.round(globalThis.winTop + Utils.getRectVerticalCenterY(rect)) + let X1 = Math.round(centerX - vp2px(66.67)); + let X2 = Math.round(centerX + vp2px(66.67)); + let Y1 = Math.round(centerY - vp2px(66.67)); + let Y2 = Math.round(centerY + vp2px(66.67)); + let stepLen = 20; + let speed = 10000; + if (isHorizontal) { + if (isForward) { + await driver.fling({ + x: X2, y: centerY + }, { + x: X1, y: centerY + }, stepLen, speed); + } else { + await driver.fling({ + x: X1, y: centerY + }, { + x: X2, y: centerY + }, stepLen, speed); + } + } else { + if (isForward) { + await driver.fling({ + x: centerX, y: Y2 + }, { + x: centerX, y: Y1 + }, stepLen, speed); + } else { + await driver.fling({ + x: centerX, y: Y1 + }, { + x: centerX, y: Y2 + }, stepLen, speed); + } + } + } + + static async clickComponent(id: string) { + let driver = Driver.create(); + let component = await driver.findComponent(ON.id(id)); + await component.click(); + } + + static async doubleClickComponent(id: string) { + let driver = Driver.create(); + let component = await driver.findComponent(ON.id(id)); + await component.click(); + await component.click(); + } + + static async clickLocation(X: number, Y: number) { + let driver = Driver.create(); + await driver.click(X, Y); + } + + static async triggerKey(id: number) { + let driver = Driver.create(); + await driver.triggerKey(id); + } + + static async longClickComponent(id: string) { + let driver = Driver.create(); + let component = await driver.findComponent(ON.id(id)); + await component.longClick(); + } + + static async clickComponentByText(text: string) { + let driver = Driver.create(); + let component = await driver.findComponent(ON.text(text)); + await component.click(); + } + + static async fingerZoom(key: string, isOut: boolean) { + let rect = Utils.getComponentRect(key); + let centerX = Math.round(globalThis.winLeft + Utils.getRectHorizontalCenterX(rect)) + let centerY = Math.round(globalThis.winTop + Utils.getRectVerticalCenterY(rect)) + let fingerUpCenterY = Math.round(centerY - vp2px(66.67)); + let fingerDownCenterY = Math.round(centerY + vp2px(66.67)); + let driver: Driver = Driver.create(); + let pointers: PointerMatrix = PointerMatrix.create(2, 3); + pointers.setPoint(0, 0, { + x: centerX, y: fingerUpCenterY - (isOut ? 40 : 120) + }); + pointers.setPoint(0, 1, { + x: centerX, y: fingerUpCenterY - 80 + }); + pointers.setPoint(0, 2, { + x: centerX, y: fingerUpCenterY - (isOut ? 120 : 40) + }); + pointers.setPoint(1, 0, { + x: centerX, y: fingerDownCenterY + (isOut ? 40 : 120) + }); + pointers.setPoint(1, 1, { + x: centerX, y: fingerDownCenterY + 80 + }); + pointers.setPoint(1, 2, { + x: centerX, y: fingerDownCenterY + (isOut ? 120 : 40) + }); + await driver.injectMultiPointerAction(pointers); + } + + static registerEvent(pageTag: string, eventId: number, callBack: Function) { + events_emitter.on({ + eventId: eventId, + priority: events_emitter.EventPriority.LOW + }, (eventData: events_emitter.EventData) => { + console.info("Value Change CallBack"); + if (eventData != null && eventData.data != null) { + if (pageTag == eventData.data.PAGE_TAG) { + console.info("CallBack value:" + JSON.stringify(eventData)); + callBack(eventData.data.VALUE); + } + } + }) + } + + static emitEvent(pageTag: string, emitValue: number | string | object, eventId: number) { + try { + let backData: events_emitter.EventData = { + data: { + "PAGE_TAG": pageTag, + "VALUE": emitValue + } + } + let backEvent: events_emitter.InnerEvent = { + eventId: eventId, + priority: events_emitter.EventPriority.LOW + } + console.info("start to emit page state"); + events_emitter.emit(backEvent, backData); + } catch (err) { + console.info("emit page state err: " + JSON.stringify(err)); + } + } + + static async pushPage(pageTag: string, done?: Function) { + let options: router.RouterOptions = { + url: `MainAbility/pages/${pageTag}`, + } + try { + router.clear(); + let pages = router.getState(); + console.info(`get ${pageTag} state success ` + JSON.stringify(pages)); + if (pageTag.indexOf(pages.name) < 0) { + console.info(`get ${pageTag} state success ` + JSON.stringify(pages.name)); + let result = await router.pushUrl(options); + await Utils.sleep(2000); + console.info(`push ${pageTag} page success ` + JSON.stringify(result)); + } + } catch (err) { + console.error(`push ${pageTag} page error: ` + err); + } + if (done) { + done(); + } + } + + static async pushPageNoClear(pageTag: string, done?: Function) { + let options: router.RouterOptions = { + url: `MainAbility/pages/${pageTag}`, + } + try { + router.pushUrl(options); + } catch (err) { + console.error(`push ${pageTag} page error: ` + err); + } + if (done) { + done(); + } + } + + static getComponentRect(key: string): Rect { + let strJson = getInspectorByKey(key); + let obj: ComponentInfo = JSON.parse(strJson); + console.info('[getInspectorByKey] key is: ' + key); + return Utils.getComponentRectByObj(obj); + } + + static getComponentRectByObj(obj: ComponentInfo): Rect { + console.info('[getInspectorByKey] current component is: ' + obj.$type); + let rectInfo: Object[] = JSON.parse('[' + obj.$rect + ']'); + let rect_value: Rect = { + left: JSON.parse('[' + rectInfo[0] + ']')[0], + top: JSON.parse('[' + rectInfo[0] + ']')[1], + right: JSON.parse('[' + rectInfo[1] + ']')[0], + bottom: JSON.parse('[' + rectInfo[1] + ']')[1] + }; + console.info(JSON.stringify(rect_value)); + return rect_value; + } + + static getComponentInfoByKey(key: string): ComponentInfo { + let strJson = getInspectorByKey(key); + let obj: ComponentInfo = JSON.parse(strJson); + console.info('[getInspectorByKey] current component info: ' + JSON.stringify(obj)); + return obj; + } + + static getRectHorizontalCenterX(rect: Rect): number { + return Number.parseInt(Number((rect.right - rect.left) / 2 + rect.left).toFixed(0)); + } + + static getRectVerticalCenterY(rect: Rect): number { + return Number.parseInt(Number((rect.bottom - rect.top) / 2 + rect.top).toFixed(0)); + } + + static async mouseMoveTo(X: number, Y: number) { + let driver = Driver.create(); + await driver.mouseMoveTo({ + x: X, y: Y + }); + } + + static getDragComponentRect(key: string) { + let strJson: string = getInspectorByKey(key); + console.info("[getInspectorByKey] current component obj is: " + JSON.stringify(JSON.parse(strJson))); + console.info("[getInspectorByKey] rectInfo is: " + JSON.parse('[' + JSON.parse(strJson).$rect + ']')); + Utils.rect_left = JSON.parse('[' + JSON.parse('[' + JSON.parse(strJson).$rect + ']')[0] + ']')[0] + Utils.rect_top = JSON.parse('[' + JSON.parse('[' + JSON.parse(strJson).$rect + ']')[0] + ']')[1] + Utils.rect_right = JSON.parse('[' + JSON.parse('[' + JSON.parse(strJson).$rect + ']')[1] + ']')[0] + Utils.rect_bottom = JSON.parse('[' + JSON.parse('[' + JSON.parse(strJson).$rect + ']')[1] + ']')[1] + return Utils.rect_value = { + left: Utils.rect_left, top: Utils.rect_top, right: Utils.rect_right, bottom: Utils.rect_bottom + } + } + + static async drag(downX: number, downY: number, upX: number, upY: number, steps: number) { + console.info('start to drag') + Utils.drags(downX, downY, upX, upY, steps, true) + } + + static async drags(downX: number, downY: number, upX: number, upY: number, steps: number, drag: boolean) { + let xStep: number; + let yStep: number; + let swipeSteps: number; + let ret: boolean; + xStep = 0; + yStep = 0; + ret = false; + swipeSteps = steps; + if (swipeSteps == 0) { + swipeSteps = 1; + } + xStep = (upX - downX) / swipeSteps; + yStep = (upY - downY) / swipeSteps; + console.info('move step is: ' + 'xStep: ' + xStep + ' yStep: ' + yStep) + let downPonit: TouchObject = { + id: 1, + x: downX, + y: downY, + type: TouchType.Down, + screenX: 0, + screenY: 0, + windowX: 0, + windowY: 0, + displayX: 0, + displayY: 0 + } + console.info('down touch started: ' + JSON.stringify(downPonit)) + sendTouchEvent(downPonit); + console.info('start to move') + if (drag) { + await Utils.sleep(500) + } + for (let i = 1; i <= swipeSteps; i++) { + let movePoint: TouchObject = { + id: 1, + x: downX + (xStep * i), + y: downY + (yStep * i), + type: TouchType.Move, + screenX: 0, + screenY: 0, + windowX: 0, + windowY: 0, + displayX: 0, + displayY: 0 + } + console.info('move touch started: ' + JSON.stringify(movePoint)) + ret = sendTouchEvent(movePoint) + if (ret == false) { + break; + } + await Utils.sleep(5) + } + console.info('start to up') + if (drag) { + await Utils.sleep(100) + } + let upPoint: TouchObject = { + id: 1, + x: upX, + y: upY, + type: TouchType.Up, + screenX: 0, + screenY: 0, + windowX: 0, + windowY: 0, + displayX: 0, + displayY: 0 + } + console.info('up touch started: ' + JSON.stringify(upPoint)) + sendTouchEvent(upPoint) + await Utils.sleep(500) + } + + static async keydo(name: string, type: number, key: number, ndkfunction: Function) { + it(name,type,async (done: Function) => { + try { + console.info(`====>${name} start<====`); + await Utils.driver.triggerKey(key); + if (key == 16) { + let com = await Utils.driver.findComponent(ON.id("KeyCodeTest1")); + await com.click(); + await com.click(); + } else if ((key > 23 && key < 2054) || (key > 23 && key < 2054) || [2626, 2627].includes(key)) { + await Utils.driver.triggerKey(1); + await Utils.simulateByShell('aa start -a MainAbility -b com.acts.keycodeevent'); + } + let KeyResult: number = ndkfunction(); + expect(KEY_CODE_EVENT_OK).assertEqual(KeyResult); + done() + } catch (err) { + console.error(`====>${name} catch err: ` + err); + expect(false).assertEqual(KEY_CODE_EVENT_ERROR); + done() + } + }) + } + + static async simulateByShell(cmd: string) { + let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); + + return new Promise((resolve, reject) => { + abilityDelegator.executeShellCommand(cmd, (err, data) => { + if (err) { + console.error(`command ${cmd} failed: ${JSON.stringify(err)}`); + reject("failed"); + } else { + console.info(`command ${cmd} executed: ${data.stdResult}`); + resolve("executed"); + } + }); + }) + } +} diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/test/mindsporetest/MindSporeFormatTest.test.ets b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/test/mindsporetest/MindSporeFormatTest.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..a1ae66ee8b838bc1bbef399676e5089e8d533578 --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/test/mindsporetest/MindSporeFormatTest.test.ets @@ -0,0 +1,371 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { describe, it, expect, TestType, Size, Level, beforeAll } from '@ohos/hypium' +import mindsporendk from 'libmindsporendk.so' + +const ARKUI_ERROR_CODE_NO_ERROR = 0; +const ARKUI_ERROR_CODE_ERROR = 1; + +export default function MindSporeFormatTest() { + describe('MindSporeFormatTest', () => { + beforeAll(async (done: Function) => { + }); + /* + * @tc.number : SUB_AI_MINDSPORE_OH_AI_FORMAT_NCHW_0100 + * @tc.name : testformattest_001 + * @tc.desc : testing OH_AI_FORMAT_NCHW interface + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 1 + */ + it('testformattest_001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: Function) => { + try { + console.info("====>testformattest_001 start===="); + let result: number = mindsporendk.FormatTest_001(); + console.info(`====>testformattest_001 result====${result}`); + expect(result).assertEqual(ARKUI_ERROR_CODE_NO_ERROR); + done(); + } catch (err) { + console.error("====>testformattest_001 err: " + err); + expect(false).assertEqual(ARKUI_ERROR_CODE_ERROR); + done(); + } + }) + + /* + * @tc.number : SUB_AI_MINDSPORE_OH_AI_FORMAT_NHWC4_0100 + * @tc.name : testformattest_002 + * @tc.desc : testing OH_AI_FORMAT_NHWC4 interface + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 1 + */ + it('testformattest_002', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: Function) => { + try { + console.info("====>testformattest_002 start===="); + let result: number = mindsporendk.FormatTest_002(); + console.info(`====>testformattest_002 result====${result}`); + expect(result).assertEqual(ARKUI_ERROR_CODE_NO_ERROR); + done(); + } catch (err) { + console.error("====>testformattest_002 err: " + err); + expect(false).assertEqual(ARKUI_ERROR_CODE_ERROR); + done(); + } + }) + + /* + * @tc.number : SUB_AI_MINDSPORE_OH_AI_FORMAT_HWCK_0100 + * @tc.name : testformattest_003 + * @tc.desc : testing OH_AI_FORMAT_HWCK interface + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 1 + */ + it('testformattest_003', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: Function) => { + try { + console.info("====>testformattest_003 start===="); + let result: number = mindsporendk.FormatTest_003(); + console.info(`====>testformattest_003 result====${result}`); + expect(result).assertEqual(ARKUI_ERROR_CODE_NO_ERROR); + done(); + } catch (err) { + console.error("====>testformattest_003 err: " + err); + expect(false).assertEqual(ARKUI_ERROR_CODE_ERROR); + done(); + } + }) + + /* + * @tc.number : SUB_AI_MINDSPORE_OH_AI_FORMAT_KCHW_0100 + * @tc.name : testformattest_004 + * @tc.desc : testing OH_AI_FORMAT_KCHW interface + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 1 + */ + it('testformattest_004', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: Function) => { + try { + console.info("====>testformattest_004 start===="); + let result: number = mindsporendk.FormatTest_004(); + console.info(`====>testformattest_004 result====${result}`); + expect(result).assertEqual(ARKUI_ERROR_CODE_NO_ERROR); + done(); + } catch (err) { + console.error("====>testformattest_004 err: " + err); + expect(false).assertEqual(ARKUI_ERROR_CODE_ERROR); + done(); + } + }) + + /* + * @tc.number : SUB_AI_MINDSPORE_OH_AI_FORMAT_CKHW_0100 + * @tc.name : testformattest_005 + * @tc.desc : testing OH_AI_FORMAT_CKHW interface + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 1 + */ + it('testformattest_005', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: Function) => { + try { + console.info("====>testformattest_005 start===="); + let result: number = mindsporendk.FormatTest_005(); + console.info(`====>testformattest_005 result====${result}`); + expect(result).assertEqual(ARKUI_ERROR_CODE_NO_ERROR); + done(); + } catch (err) { + console.error("====>testformattest_005 err: " + err); + expect(false).assertEqual(ARKUI_ERROR_CODE_ERROR); + done(); + } + }) + + /* + * @tc.number : SUB_AI_MINDSPORE_OH_AI_FORMAT_KHWC_0100 + * @tc.name : testformattest_006 + * @tc.desc : testing OH_AI_FORMAT_KHWC interface + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 1 + */ + it('testformattest_006', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: Function) => { + try { + console.info("====>testformattest_006 start===="); + let result: number = mindsporendk.FormatTest_006(); + console.info(`====>testformattest_006 result====${result}`); + expect(result).assertEqual(ARKUI_ERROR_CODE_NO_ERROR); + done(); + } catch (err) { + console.error("====>testformattest_006 err: " + err); + expect(false).assertEqual(ARKUI_ERROR_CODE_ERROR); + done(); + } + }) + + /* + * @tc.number : SUB_AI_MINDSPORE_OH_AI_FORMAT_CHWK_0100 + * @tc.name : testformattest_007 + * @tc.desc : testing OH_AI_FORMAT_CHWK interface + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 1 + */ + it('testformattest_007', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: Function) => { + try { + console.info("====>testformattest_007 start===="); + let result: number = mindsporendk.FormatTest_007(); + console.info(`====>testformattest_007 result====${result}`); + expect(result).assertEqual(ARKUI_ERROR_CODE_NO_ERROR); + done(); + } catch (err) { + console.error("====>testformattest_007 err: " + err); + expect(false).assertEqual(ARKUI_ERROR_CODE_ERROR); + done(); + } + }) + + /* + * @tc.number : SUB_AI_MINDSPORE_OH_AI_FORMAT_HW_0100 + * @tc.name : testformattest_008 + * @tc.desc : testing OH_AI_FORMAT_HW interface + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 1 + */ + it('testformattest_008', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: Function) => { + try { + console.info("====>testformattest_008 start===="); + let result: number = mindsporendk.FormatTest_008(); + console.info(`====>testformattest_008 result====${result}`); + expect(result).assertEqual(ARKUI_ERROR_CODE_NO_ERROR); + done(); + } catch (err) { + console.error("====>testformattest_008 err: " + err); + expect(false).assertEqual(ARKUI_ERROR_CODE_ERROR); + done(); + } + }) + + /* + * @tc.number : SUB_AI_MINDSPORE_OH_AI_FORMAT_HW4_0100 + * @tc.name : testformattest_009 + * @tc.desc : testing OH_AI_FORMAT_HW4 interface + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 1 + */ + it('testformattest_009', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: Function) => { + try { + console.info("====>testformattest_009 start===="); + let result: number = mindsporendk.FormatTest_009(); + console.info(`====>testformattest_009 result====${result}`); + expect(result).assertEqual(ARKUI_ERROR_CODE_NO_ERROR); + done(); + } catch (err) { + console.error("====>testformattest_009 err: " + err); + expect(false).assertEqual(ARKUI_ERROR_CODE_ERROR); + done(); + } + }) + + /* + * @tc.number : SUB_AI_MINDSPORE_OH_AI_FORMAT_NC_0100 + * @tc.name : testformattest_010 + * @tc.desc : testing OH_AI_FORMAT_NC interface + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 1 + */ + it('testformattest_010', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: Function) => { + try { + console.info("====>testformattest_010 start===="); + let result: number = mindsporendk.FormatTest_010(); + console.info(`====>testformattest_010 result====${result}`); + expect(result).assertEqual(ARKUI_ERROR_CODE_NO_ERROR); + done(); + } catch (err) { + console.error("====>testformattest_010 err: " + err); + expect(false).assertEqual(ARKUI_ERROR_CODE_ERROR); + done(); + } + }) + + /* + * @tc.number : SUB_AI_MINDSPORE_OH_AI_FORMAT_NC4_0100 + * @tc.name : testformattest_011 + * @tc.desc : testing OH_AI_FORMAT_NC4 interface + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 1 + */ + it('testformattest_011', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: Function) => { + try { + console.info("====>testformattest_011 start===="); + let result: number = mindsporendk.FormatTest_011(); + console.info(`====>testformattest_011 result====${result}`); + expect(result).assertEqual(ARKUI_ERROR_CODE_NO_ERROR); + done(); + } catch (err) { + console.error("====>testformattest_011 err: " + err); + expect(false).assertEqual(ARKUI_ERROR_CODE_ERROR); + done(); + } + }) + + /* + * @tc.number : SUB_AI_MINDSPORE_OH_AI_FORMAT_NC4HW4_0100 + * @tc.name : testformattest_012 + * @tc.desc : testing OH_AI_FORMAT_NC4HW4 interface + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 1 + */ + it('testformattest_012', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: Function) => { + try { + console.info("====>testformattest_012 start===="); + let result: number = mindsporendk.FormatTest_012(); + console.info(`====>testformattest_012 result====${result}`); + expect(result).assertEqual(ARKUI_ERROR_CODE_NO_ERROR); + done(); + } catch (err) { + console.error("====>testformattest_012 err: " + err); + expect(false).assertEqual(ARKUI_ERROR_CODE_ERROR); + done(); + } + }) + + /* + * @tc.number : SUB_AI_MINDSPORE_OH_AI_FORMAT_NCDHW_0100 + * @tc.name : testformattest_013 + * @tc.desc : testing OH_AI_FORMAT_NCDHW interface + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 1 + */ + it('testformattest_013', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: Function) => { + try { + console.info("====>testformattest_013 start===="); + let result: number = mindsporendk.FormatTest_013(); + console.info(`====>testformattest_013 result====${result}`); + expect(result).assertEqual(ARKUI_ERROR_CODE_NO_ERROR); + done(); + } catch (err) { + console.error("====>testformattest_013 err: " + err); + expect(false).assertEqual(ARKUI_ERROR_CODE_ERROR); + done(); + } + }) + + /* + * @tc.number : SUB_AI_MINDSPORE_OH_AI_FORMAT_NWC_0100 + * @tc.name : testformattest_014 + * @tc.desc : testing OH_AI_FORMAT_NWC interface + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 1 + */ + it('testformattest_014', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: Function) => { + try { + console.info("====>testformattest_014 start===="); + let result: number = mindsporendk.FormatTest_014(); + console.info(`====>testformattest_014 result====${result}`); + expect(result).assertEqual(ARKUI_ERROR_CODE_NO_ERROR); + done(); + } catch (err) { + console.error("====>testformattest_014 err: " + err); + expect(false).assertEqual(ARKUI_ERROR_CODE_ERROR); + done(); + } + }) + + /* + * @tc.number : SUB_AI_MINDSPORE_OH_AI_FORMAT_NCW_0100 + * @tc.name : testformattest_015 + * @tc.desc : testing OH_AI_FORMAT_NCW interface + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 1 + */ + it('testformattest_015', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: Function) => { + try { + console.info("====>testformattest_015 start===="); + let result: number = mindsporendk.FormatTest_015(); + console.info(`====>testformattest_015 result====${result}`); + expect(result).assertEqual(ARKUI_ERROR_CODE_NO_ERROR); + done(); + } catch (err) { + console.error("====>testformattest_015 err: " + err); + expect(false).assertEqual(ARKUI_ERROR_CODE_ERROR); + done(); + } + }) + }) +} diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/testrunner/OpenHarmonyTestRunner.ts b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/testrunner/OpenHarmonyTestRunner.ts new file mode 100644 index 0000000000000000000000000000000000000000..98c90db98dcd86acbac04911f613b9526aa852bd --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/ets/testrunner/OpenHarmonyTestRunner.ts @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import hilog from '@ohos.hilog'; +import TestRunner from '@ohos.application.testRunner'; +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; + +var abilityDelegator = undefined +var abilityDelegatorArguments = undefined + +async function onAbilityCreateCallback() { + hilog.info(0x0000, 'testTag', '%{public}s', 'onAbilityCreateCallback'); +} + +async function addAbilityMonitorCallback(err: any) { + hilog.info(0x0000, 'testTag', 'addAbilityMonitorCallback : %{public}s', JSON.stringify(err) ?? ''); +} + +export default class OpenHarmonyTestRunner implements TestRunner { + constructor() { + } + + onPrepare() { + hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner OnPrepare '); + } + + async onRun() { + hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner onRun run'); + abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments() + abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator() + var testAbilityName = abilityDelegatorArguments.bundleName + '.MainAbility' + let lMonitor = { + abilityName: testAbilityName, + onAbilityCreate: onAbilityCreateCallback, + }; + abilityDelegator.addAbilityMonitor(lMonitor, addAbilityMonitorCallback) + var cmd = 'aa start -d 0 -a MainAbility' + ' -b ' + abilityDelegatorArguments.bundleName + var debug = abilityDelegatorArguments.parameters['-D'] + if (debug == 'true') + { + cmd += ' -D' + } + hilog.info(0x0000, 'testTag', 'cmd : %{public}s', cmd); + abilityDelegator.executeShellCommand(cmd, + (err: any, d: any) => { + hilog.info(0x0000, 'testTag', 'executeShellCommand : err : %{public}s', JSON.stringify(err) ?? ''); + hilog.info(0x0000, 'testTag', 'executeShellCommand : data : %{public}s', d.stdResult ?? ''); + hilog.info(0x0000, 'testTag', 'executeShellCommand : data : %{public}s', d.exitCode ?? ''); + }) + hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner onRun end'); + } +} \ No newline at end of file diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/module.json5 b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/module.json5 new file mode 100644 index 0000000000000000000000000000000000000000..6a51bc8195414a7ed0d1ff58defc13a627c9eb36 --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/module.json5 @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "module": { + "name": "entry_test", + "type": "feature", + "description": "$string:module_test_desc", + "mainElement": "MainAbility", + "deviceTypes": [], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:main_pages", + "abilities": [ + { + "name": "MainAbility", + "srcEntry": "./ets/MainAbility/MainAbility.ts", + "description": "$string:TestAbility_desc", + "icon": "$media:icon", + "label": "$string:TestAbility_label", + "launchType": "singleton", + "exported": true, + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:start_window_background", + "skills": [ + { + "actions": [ + "action.system.home" + ], + "entities": [ + "entity.system.home" + ] + } + ] + } + ] + } +} diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/resources/base/element/color.json b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/resources/base/element/color.json new file mode 100644 index 0000000000000000000000000000000000000000..3c712962da3c2751c2b9ddb53559afcbd2b54a02 --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/resources/base/element/color.json @@ -0,0 +1,8 @@ +{ + "color": [ + { + "name": "start_window_background", + "value": "#FFFFFF" + } + ] +} \ No newline at end of file diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/resources/base/element/string.json b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..65d8fa5a7cf54aa3943dcd0214f58d1771bc1f6c --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/resources/base/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_test_desc", + "value": "test ability description" + }, + { + "name": "TestAbility_desc", + "value": "the test ability" + }, + { + "name": "TestAbility_label", + "value": "test label" + } + ] +} \ No newline at end of file diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/resources/base/media/icon.png b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/resources/base/media/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/resources/base/profile/main_pages.json b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/resources/base/profile/main_pages.json new file mode 100644 index 0000000000000000000000000000000000000000..7ad8ced45ea4c6169064dbf082692de5e603e03d --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/resources/base/profile/main_pages.json @@ -0,0 +1,5 @@ +{ + "src": [ + "MainAbility/pages/XTSIndex" + ] +} \ No newline at end of file diff --git a/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/syscap.json b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/syscap.json new file mode 100644 index 0000000000000000000000000000000000000000..d05ea9d7d5152602692ab3fc23d5fba0590adff3 --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/entry/src/ohosTest/syscap.json @@ -0,0 +1,14 @@ +{ + "devices": { + "general": [], + "custom": [ + { + "xts": [ + "SystemCapability.Account.OsAccount", + "SystemCapability.Security.AccessToken", + "SystemCapability.Ai.MindSpore" + ] + } + ] + } +} \ No newline at end of file diff --git a/ai/mindspore/ai_mindsporectest_20/hvigor/hvigor-config.json5 b/ai/mindspore/ai_mindsporectest_20/hvigor/hvigor-config.json5 new file mode 100644 index 0000000000000000000000000000000000000000..006374173a4ca5cdca753c1fc58b39c1dc23c558 --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/hvigor/hvigor-config.json5 @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "modelVersion": "5.0.0", + "dependencies": { + } +} \ No newline at end of file diff --git a/ai/mindspore/ai_mindsporectest_20/hvigorfile.ts b/ai/mindspore/ai_mindsporectest_20/hvigorfile.ts new file mode 100644 index 0000000000000000000000000000000000000000..8ed8b76b012ef4ecbd77d9848a82ac26f886d64b --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/hvigorfile.ts @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently. +export { appTasks } from '@ohos/hvigor-ohos-plugin'; \ No newline at end of file diff --git a/ai/mindspore/ai_mindsporectest_20/oh-package.json5 b/ai/mindspore/ai_mindsporectest_20/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..aaa9b7a6eb604ba2f44d9d1395f2269a44f381f8 --- /dev/null +++ b/ai/mindspore/ai_mindsporectest_20/oh-package.json5 @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +{ + "modelVersion": "5.0.0", + "license": "", + "devDependencies": { + "@ohos/hypium": "1.0.6" + }, + "author": "", + "name": "ActsMindSporec20Test", + "description": "Please describe the basic information.", + "main": "", + "version": "1.0.0", + "dependencies": {} +} \ No newline at end of file diff --git a/ai/mindspore/ai_mindsporectest_20/signature/openharmony_sx.p7b b/ai/mindspore/ai_mindsporectest_20/signature/openharmony_sx.p7b new file mode 100644 index 0000000000000000000000000000000000000000..00f4625f85b6f86fb1871d7fd375a6696be6ed1d Binary files /dev/null and b/ai/mindspore/ai_mindsporectest_20/signature/openharmony_sx.p7b differ diff --git a/arkui/ace_ets_module_ui/ace_ets_module_commonAttrsLayout/ace_ets_module_commonAttrsLayout_api11/entry/src/main/ets/MainAbility/pages/comSizeAbility/comSizeAbilityTest_07.ets b/arkui/ace_ets_module_ui/ace_ets_module_commonAttrsLayout/ace_ets_module_commonAttrsLayout_api11/entry/src/main/ets/MainAbility/pages/comSizeAbility/comSizeAbilityTest_07.ets index 29a9a65fd757429356c0c4254bd08044886ab2a0..5138ce057365ea597bf9961a5b8743737d1831d3 100644 --- a/arkui/ace_ets_module_ui/ace_ets_module_commonAttrsLayout/ace_ets_module_commonAttrsLayout_api11/entry/src/main/ets/MainAbility/pages/comSizeAbility/comSizeAbilityTest_07.ets +++ b/arkui/ace_ets_module_ui/ace_ets_module_commonAttrsLayout/ace_ets_module_commonAttrsLayout_api11/entry/src/main/ets/MainAbility/pages/comSizeAbility/comSizeAbilityTest_07.ets @@ -125,21 +125,26 @@ struct comSizeAbilityTest_07 { Button(`ShowSize: MenuItemGroup`) .fontSize(16) .margin(5) - .bindMenu(this.MyMenu1) .key('btn_MenuItemGroup') - .bindMenu(this.MyMenu1) + .bindMenu(this.MyMenu1, { + showInSubWindow: false + }) } Column() { Button(`ShowSize: MenuItem`).fontSize(16).margin(5) .key('btn_MenuItem') - .bindMenu(this.MyMenu2) + .bindMenu(this.MyMenu2, { + showInSubWindow: false + }) } Column() { Button(`ShowSize: Menu`).fontSize(16).margin(5) .key('btn_Menu') - .bindMenu(this.MyMenu3) + .bindMenu(this.MyMenu3, { + showInSubWindow: false + }) } }.width('100%') }.height('100%') diff --git a/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/List.test.ets b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/List.test.ets index 829f0e3a278beee4f844835289870114b04eab89..ffc5e0274a8de70c908989ad850261e739d03ffd 100644 --- a/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/List.test.ets +++ b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/List.test.ets @@ -41,6 +41,17 @@ import expressionTest4 from './expression/ExpressionTest4.test'; import looper1Test from './looper/Looper1.test'; import looper2Test from './looper/Looper2.test'; import looper3Test from './looper/Looper3.test'; +import indexArrayCreateTest from './indexArray/IndexArrayCreate.test'; +import indexArrayFillTest from './indexArray/IndexArrayFill.test'; +import indexArrayMulArrTest from './indexArray/IndexArrayMulArr.test'; +import indexArraySparseTest from './indexArray/IndexArraySparse.test'; +import objectAllPropTest from './object/ObjectAllProp.test'; +import objectAndPropTest from './object/ObjectAndProp.test'; +import builtinsStatementObjectCompareTest from './object/ObjectCompare.test'; +import objectExtendsTest from './object/ObjectExtends.test'; +import objectFunctionTest from './object/ObjectFunction.test'; +import objectGetSetTest from './object/ObjectGetSet.test'; +import objectIndexTest from './object/ObjectIndex.test'; import typeArrayBigInt64ArrayTest from "./typearray/TypeArrayBigInt64Array.test"; export default function testsuite() { @@ -72,4 +83,15 @@ export default function testsuite() { looper3Test(); RegExpTest(); KeyCollectionTest(); + objectAndPropTest(); + objectExtendsTest(); + objectIndexTest(); + objectFunctionTest(); + objectGetSetTest(); + builtinsStatementObjectCompareTest(); + objectAllPropTest(); + indexArrayCreateTest(); + indexArrayFillTest(); + indexArraySparseTest(); + indexArrayMulArrTest(); } diff --git a/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/indexArray/IndexArrayCreate.js b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/indexArray/IndexArrayCreate.js new file mode 100644 index 0000000000000000000000000000000000000000..9aa4588c2c6c0a758508698aea0e1effa6a46535 --- /dev/null +++ b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/indexArray/IndexArrayCreate.js @@ -0,0 +1,98 @@ +export function indexArrayCreateTest0600(arr){ + return arr.hasOwnProperty('2'); +} + +export function indexArrayCreateTest0900(){ + const obj1 = {}; + obj1.fruits = ['apple', 'banana']; + return obj1; +} +export function indexArrayCreateTest0901(){ + const obj2 = { + scores: [90, 85, 95], + info: { tags: ['test', 'array'] } + }; + return obj2; +} + +export function indexArrayCreateTest1400(){ + const arr1 = [10, 20, 30]; + delete arr1[1]; + return arr1; +} + +export function indexArrayCreateTest1600(){ + const arr = []; + arr[0] = 'a'; + arr[2] = 'c'; + const indices = []; + for (const idx in arr) { + indices.push(idx); + } + return indices; +} + +export function indexArrayCreateTest1700(){ + const arr = [ + 'string', 123, true, null, undefined, + { key: 'value' }, () => {} + ]; + return arr; +} + +export function indexArrayCreateTest1900(arr){ + delete arr[1]; +} + +export function indexArrayCreateTest2100(arr){ + return [arr.hasOwnProperty('1'), arr.hasOwnProperty('3')] +} + +export function indexArrayCreateTest2700(arr){ + return [0 in arr, 2 in arr, 3 in arr]; +} + +export function indexArrayCreateTest4100(){ + const arrayLike = { + 0: 'a', + 1: 'b', + 2: 'c', + length: 3 + }; + return [arrayLike, arrayLike[0]]; +} + +export function indexArrayCreateTest4200(){ + const arrayLike = { + 0: 10, + 1: 20, + 2: 30, + length: 3 + }; + const arr1 = Array.from(arrayLike); + const arr2 = Array.prototype.slice.call(arrayLike); + return [arr1, arr2]; +} + +export function indexArrayCreateTest4300(){ + const arr = [1, 2, 3]; + arr.customName = 'testArray'; + arr.version = '1.0'; + return arr; +} + +export function indexArrayCreateTest4400(){ + const arr = [10, 20, 30]; + arr.label = 'numbers'; + const forInKeys = []; + for (const key in arr) { + forInKeys.push(key); + } + + const forOfItems = []; + for (const item of arr) { + forOfItems.push(item); + } + + return [forInKeys, forOfItems] +} \ No newline at end of file diff --git a/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/indexArray/IndexArrayCreate.test.ets b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/indexArray/IndexArrayCreate.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..734c91a0ef9801357d935fee3382a014b0625822 --- /dev/null +++ b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/indexArray/IndexArrayCreate.test.ets @@ -0,0 +1,893 @@ +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, TestType, Level, Size } from '@ohos/hypium'; +import { indexArrayCreateTest0600, indexArrayCreateTest0900, indexArrayCreateTest0901, + indexArrayCreateTest1400, + indexArrayCreateTest1600, + indexArrayCreateTest1700, + indexArrayCreateTest1900, + indexArrayCreateTest2100, + indexArrayCreateTest2700, + indexArrayCreateTest4100, + indexArrayCreateTest4200, + indexArrayCreateTest4300, + indexArrayCreateTest4400} from './IndexArrayCreate'; + +function sleep(time: number): Promise { + return new Promise((re, je) => { + setTimeout(() => { + re(); + }, time); + }); +} + +type NestedNumberArray = number | NestedNumberArray[]; +function deepClone(arr: NestedNumberArray[]): NestedNumberArray[] { + return arr.map(item => Array.isArray(item) ? deepClone(item) : item); +} + +export default function indexArrayCreateTest() { + describe('indexArrayCreateTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }) + beforeEach(async () => { + await sleep(100); + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }) + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }) + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }) + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_0100 + * @tc.name indexArrayCreateTest0100 + * @tc.desc Create a multi-element array with array literals + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest0100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = ['apple', 100, true, null, undefined]; + expect(Array.isArray(arr)).assertEqual(true); + expect(arr.length).assertEqual(5); + expect(arr[0]).assertEqual('apple'); + expect(arr[2]).assertEqual(true); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_0200 + * @tc.name indexArrayCreateTest0200 + * @tc.desc Create a single element array with array literals + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest0200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const numArr = [42]; + expect(numArr.length).assertEqual(1); + expect(numArr[0]).assertEqual(42); + + const strArr = ['test']; + expect(strArr.length).assertEqual(1); + expect(strArr[0]).assertEqual('test'); + + interface BaseI{ + name: string; + } + const objArr = [{ name: 'array' } as BaseI]; + expect(objArr.length).assertEqual(1); + expect(objArr[0].name).assertEqual('array'); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_0300 + * @tc.name indexArrayCreateTest0300 + * @tc.desc Create a multi-element array using 'new Arrange()' + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest0300', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = new Array('banana', 200, false); + expect(Array.isArray(arr)).assertEqual(true); + expect(arr.length).assertEqual(3); + expect(arr[1]).assertEqual(200); + expect(arr[2]).assertEqual(false); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_0400 + * @tc.name indexArrayCreateTest0400 + * @tc.desc New Arrange() creates an empty array of specified length + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest0400', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = new Array(5); + expect(arr.length).assertEqual(5); + expect(arr[0]).assertUndefined(); + expect(Object.keys(arr).length).assertEqual(0); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_0500 + * @tc.name indexArrayCreateTest0500 + * @tc.desc Arrange() creates an array without new + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest0500', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr1 = Array('cat', 300); + expect(arr1.length).assertEqual(2); + expect(arr1[0]).assertEqual('cat'); + + const arr2 = Array(3); + expect(arr2.length).assertEqual(3); + expect(arr2[1]).assertUndefined(); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_0600 + * @tc.name indexArrayCreateTest0600 + * @tc.desc Dynamically set the length to create an array + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest0600', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr: string[] = []; + arr.length = 4; + expect(arr.length).assertEqual(4); + expect(arr[2]).assertUndefined(); + let hasOwn = indexArrayCreateTest0600(arr) as boolean; + expect(hasOwn).assertEqual(false); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_0700 + * @tc.name indexArrayCreateTest0700 + * @tc.desc Array. of() creates a single element array + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest0700', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const numArr = Array.of(9.3); + expect(numArr.length).assertEqual(1); + expect(numArr[0]).assertEqual(9.3); + + const boolArr = Array.of(true); + expect(boolArr.length).assertEqual(1); + expect(boolArr[0]).assertEqual(true); + + const mixArr = Array.of('dog', 400, null); + expect(mixArr.length).assertEqual(3); + expect(mixArr[2]).assertNull(); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_0800 + * @tc.name indexArrayCreateTest0800 + * @tc.desc Non integer length error + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest0800', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + expect(() => new Array(9.3)).assertThrowError(RangeError); + expect(() => Array(5.7)).assertThrowError(RangeError); + expect(() => { + const arr: object[] = []; + arr.length = 3.2; + }).assertThrowError(RangeError); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_0900 + * @tc.name indexArrayCreateTest0900 + * @tc.desc Array as object property + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest0900', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const obj1 = indexArrayCreateTest0900() + expect(obj1.fruits.length).assertEqual(2); + expect(obj1.fruits[1]).assertEqual('banana'); + + const obj2 = indexArrayCreateTest0901(); + expect(obj2.scores[0]).assertEqual(90); + expect(obj2.info.tags[1]).assertEqual('array'); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_1000 + * @tc.name indexArrayCreateTest1000 + * @tc.desc Ultra long length array + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + // it('indexArrayCreateTest1000', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + // const maxSafeInt = Number.MAX_SAFE_INTEGER; + // const safeArr = new Array(maxSafeInt); + // expect(safeArr.length).assertEqual(maxSafeInt); + // + // const unsafeArr = new Array(maxSafeInt + 1); + // expect(unsafeArr.length).assertEqual(maxSafeInt + 1); + // expect(unsafeArr[maxSafeInt + 1]).assertUndefined(); + // }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_1100 + * @tc.name indexArrayCreateTest1100 + * @tc.desc Forward index access element + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest1100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = ['a', 'b', 'c', 'd']; + expect(arr[0]).assertEqual('a'); + expect(arr[2]).assertEqual('c'); + expect(arr[3]).assertEqual('d'); + expect(arr[4]).assertUndefined(); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_1200 + * @tc.name indexArrayCreateTest1200 + * @tc.desc Negative index access element + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest1200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [10, 20, 30, 40]; + expect(arr[-1]).assertUndefined(); + expect(arr[arr.length - 1]).assertEqual(40); + expect(arr[arr.length - 2]).assertEqual(30); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_1300 + * @tc.name indexArrayCreateTest1300 + * @tc.desc Element assignment and modification + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest1300', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, 2, 3]; + arr[1] = 20; + expect(arr[1]).assertEqual(20); + + arr[5] = 50; + expect(arr[5]).assertEqual(50); + expect(arr.length).assertEqual(6); + expect(arr[3]).assertUndefined(); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_1400 + * @tc.name indexArrayCreateTest1400 + * @tc.desc Delete array elements + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest1400', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr1 = indexArrayCreateTest1400(); + expect(arr1[1]).assertUndefined(); + expect(arr1.length).assertEqual(3); + + const arr2 = [10, 20, 30]; + arr2.splice(1, 1); + expect(arr2[1]).assertEqual(30); + expect(arr2.length).assertEqual(2); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_1500 + * @tc.name indexArrayCreateTest1500 + * @tc.desc Read and write properties of the length attribute + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest1500', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, 2, 3]; + expect(arr.length).assertEqual(3); + + arr.length = 2; + expect(arr.length).assertEqual(2); + expect(arr[2]).assertUndefined(); + + arr.length = 5; + expect(arr.length).assertEqual(5); + expect(arr[3]).assertUndefined(); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_1600 + * @tc.name indexArrayCreateTest1600 + * @tc.desc For... in Traversing Sparse Arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest1600', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const indices: string[] = indexArrayCreateTest1600(); + expect(indices).assertDeepEquals(['0', '2']); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_1700 + * @tc.name indexArrayCreateTest1700 + * @tc.desc Array element type check + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest1700', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = indexArrayCreateTest1700(); + expect(typeof arr[0]).assertEqual('string'); + expect(typeof arr[1]).assertEqual('number'); + expect(typeof arr[5]).assertEqual('object'); + expect(typeof arr[6]).assertEqual('function'); + expect(arr[3]).assertNull(); + expect(arr[4]).assertUndefined(); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_1800 + * @tc.name indexArrayCreateTest1800 + * @tc.desc Array element reference passing + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest1800', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface BaseI{ + name: string; + } + const obj : BaseI = { name: 'test' }; + const arr = [obj, 100]; + obj.name = 'modified'; + expect((arr[0] as BaseI).name).assertEqual('modified'); + + arr[0] = { name: 'new' }; + expect(obj.name).assertEqual('modified'); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_1900 + * @tc.name indexArrayCreateTest1900 + * @tc.desc Empty array operation + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest1900', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr: string[] = []; + expect(arr.length).assertEqual(0); + expect(arr[0]).assertUndefined(); + + arr[0] = 'first'; + expect(arr.length).assertEqual(1); + expect(arr[0]).assertEqual('first'); + + indexArrayCreateTest1900(arr); + expect(arr.length).assertEqual(1); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_2000 + * @tc.name indexArrayCreateTest2000 + * @tc.desc Batch operation of array elements + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest2000', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr1 = new Array(3); + arr1.fill(5); + expect(arr1).assertDeepEquals([5, 5, 5]); + + const arr2 = [1, , 3]; + const mapped = arr2.map((item) => item ? item * 2 : item); + expect(mapped).assertDeepEquals([2, , 6]); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_2100 + * @tc.name indexArrayCreateTest2100 + * @tc.desc Basic characteristics of sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest2100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr: string[] = []; + arr[0] = 'x'; + arr[3] = 'y'; + expect(arr.length).assertEqual(4); + expect(arr[1]).assertUndefined(); + + const result = indexArrayCreateTest2100(arr) as boolean[]; + expect(result[0]).assertEqual(false); + expect(result[1]).assertEqual(true); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_2200 + * @tc.name indexArrayCreateTest2200 + * @tc.desc Sparse arrays and array methods + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest2200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3, , 5]; + const forEachVals: (number | undefined)[] = []; + arr.forEach((val) => forEachVals.push(val)); + expect(forEachVals).assertDeepEquals([1, 3, 5]); + + const mapped = arr.map((val) => val ? val * 2 : val); + expect(mapped).assertDeepEquals([2, , 6, , 10]); + + const filtered = arr.filter((val) => val? val > 2 : false); + expect(filtered).assertDeepEquals([3, 5]); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_2300 + * @tc.name indexArrayCreateTest2300 + * @tc.desc Length adjustment of sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest2300', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr: string[] = []; + arr[5] = 'a'; + expect(arr.length).assertEqual(6); + + arr.length = 3; + expect(arr[5]).assertUndefined(); + expect(arr.length).assertEqual(3); + + arr.length = 10; + expect(arr[7]).assertUndefined(); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_2400 + * @tc.name indexArrayCreateTest2400 + * @tc.desc Convert sparse array to dense array + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest2400', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3]; + + const filled = arr.fill(0); + expect(filled).assertDeepEquals([0, 0, 0]); + + const arr2 = [1, , 3]; + const dense = Array.from(arr2); + expect(dense).assertDeepEquals([1, undefined, 3]); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_2500 + * @tc.name indexArrayCreateTest2500 + * @tc.desc JSON serialization of sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest2500', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3]; + const json = JSON.stringify(arr); + expect(json).assertEqual('[1,null,3]'); + + const parsed = JSON.parse(json) as (number | undefined)[]; + expect(parsed.toString()).assertEqual([1, null, 3].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_2600 + * @tc.name indexArrayCreateTest2600 + * @tc.desc Ultra long sparse array + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest2600', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr: string[] = []; + arr[10000] = 'test'; + expect(arr.length).assertEqual(10001); + expect(arr[9999]).assertUndefined(); + expect(arr[10000]).assertEqual('test'); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_2700 + * @tc.name indexArrayCreateTest2700 + * @tc.desc Sparse array and in operator + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest2700', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr: string[] = []; + arr[2] = 'val'; + const result = indexArrayCreateTest2700(arr); + expect(result[0]).assertEqual(false); + expect(result[1]).assertEqual(true); + expect(result[2]).assertEqual(false); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_2800 + * @tc.name indexArrayCreateTest2800 + * @tc.desc Concat operation on sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest2800', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr1 = [1, , 3]; + const arr2 = [4, 5]; + const concatenated = arr1.concat(arr2); + expect(concatenated.toString()).assertEqual([1, , 3, 4, 5].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_2900 + * @tc.name indexArrayCreateTest2900 + * @tc.desc Slice operation of sparse array + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest2900', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3, , 5]; + const sliced = arr.slice(1, 4); + expect(sliced.toString()).assertEqual([, 3, ,].toString()); + expect(sliced.length).assertEqual(3); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_3000 + * @tc.name indexArrayCreateTest3000 + * @tc.desc Reduce operations on sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest3000', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3, , 5]; + const sum = arr.reduce((acc, val) => { + if (acc) { + console.log('acc: ' + acc + ' val: ' + val) + if (val) { + return acc + val; + } + return acc; + } + return 0; + }); + expect(sum).assertEqual(9); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_3100 + * @tc.name indexArrayCreateTest3100 + * @tc.desc 2D array creation and access + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest3100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const twoDArr = [ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9] + ]; + expect(twoDArr.length).assertEqual(3); + expect(twoDArr[0].length).assertEqual(3); + expect(twoDArr[1][2]).assertEqual(6); + + twoDArr[2][0] = 70; + expect(twoDArr[2][0]).assertEqual(70); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_3200 + * @tc.name indexArrayCreateTest3200 + * @tc.desc 3D array creation and access + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest3200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const threeDArr = [ + [ + [1, 2], + [3, 4] + ], + [ + [5, 6], + [7, 8] + ] + ]; + expect(threeDArr[0][1][0]).assertEqual(3); + expect(threeDArr[1][0][1]).assertEqual(6); + + threeDArr[1][1][1] = 80; + expect(threeDArr[1][1][1]).assertEqual(80); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_3300 + * @tc.name indexArrayCreateTest3300 + * @tc.desc Irregular multidimensional array + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest3300', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const jaggedArr = [ + [1, 2], + [3], + [4, 5, 6] + ]; + expect(jaggedArr[0].length).assertEqual(2); + expect(jaggedArr[1].length).assertEqual(1); + expect(jaggedArr[2][2]).assertEqual(6); + expect(jaggedArr[1][1]).assertUndefined(); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_3400 + * @tc.name indexArrayCreateTest3400 + * @tc.desc Multidimensional array reference feature + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest3400', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const nestedArr = [1, 2]; + const twoDArr = [nestedArr, [3, 4]]; + nestedArr[0] = 10; + expect(twoDArr[0][0]).assertEqual(10); + + twoDArr[0] = [100, 200]; + expect(nestedArr[0]).assertEqual(10); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_3500 + * @tc.name indexArrayCreateTest3500 + * @tc.desc Traverse multidimensional arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest3500', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const twoDArr = [ + [1, 2, 3], + [4, 5, 6] + ]; + const flatValues: number[] = []; + for (let i = 0; i < twoDArr.length; i++) { + for (let j = 0; j < twoDArr[i].length; j++) { + flatValues.push(twoDArr[i][j]); + } + } + expect(flatValues.toString()).assertEqual([1, 2, 3, 4, 5, 6].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_3600 + * @tc.name indexArrayCreateTest3600 + * @tc.desc Flattening multidimensional arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest3600', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const threeDArr = [1, [2, [3, [4]]]]; + expect(threeDArr.flat(1).toString()).assertEqual([1, 2, [3, [4]]].toString()); + expect(threeDArr.flat(2).toString()).assertEqual([1, 2, 3, [4]].toString()); + expect(threeDArr.flat(Infinity).toString()).assertEqual([1, 2, 3, 4].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_3700 + * @tc.name indexArrayCreateTest3700 + * @tc.desc Dynamically create multidimensional arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest3700', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const rows = 3; + const cols = 3; + const twoDArr: number[][] = []; + for (let i = 0; i < rows; i++) { + twoDArr[i] = []; + for (let j = 0; j < cols; j++) { + twoDArr[i][j] = 0; + } + } + expect(twoDArr[1][1]).assertEqual(0); + expect(twoDArr.length).assertEqual(3); + expect(twoDArr[2].length).assertEqual(3); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_3800 + * @tc.name indexArrayCreateTest3800 + * @tc.desc Multidimensional array shallow copy + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest3800', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const original = [[1, 2], [3, 4]]; + const shallowCopy = [...original]; + shallowCopy[0][0] = 10; + expect(original[0][0]).assertEqual(10); + + shallowCopy[1] = [30, 40]; + expect(original[1][0]).assertEqual(3); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_3900 + * @tc.name indexArrayCreateTest3900 + * @tc.desc Multidimensional array deep copy + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest3900', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const original = [[1, 2], [3, [4, 5]]]; + const deepCopy = deepClone(original); + (deepCopy[0] as NestedNumberArray[])[0] = 10; + ((deepCopy[1] as NestedNumberArray[])[1] as NestedNumberArray[])[0] = 40; + expect(original[0][0]).assertEqual(1); + expect(((original[1] as NestedNumberArray[])[1] as NestedNumberArray[])[0]).assertEqual(4); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_4000 + * @tc.name indexArrayCreateTest4000 + * @tc.desc Multidimensional array JSON serialization + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest4000', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const twoDArr = [ + [1, 2], + [3, 4] + ]; + const jsonStr = JSON.stringify(twoDArr); + expect(jsonStr).assertEqual('[[1,2],[3,4]]'); + + const parsedArr = JSON.parse(jsonStr) as number[][]; + expect(parsedArr.toString()).assertEqual(twoDArr.toString()); + parsedArr[0][0] = 100; + expect(twoDArr[0][0]).assertEqual(1); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_4100 + * @tc.name indexArrayCreateTest4100 + * @tc.desc Basic characteristics of class array objects + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest4100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const result = indexArrayCreateTest4100(); + expect(result[1]).assertEqual('a'); + expect(result[0].length).assertEqual(3); + expect(Array.isArray(result[0])).assertEqual(false); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_4200 + * @tc.name indexArrayCreateTest4200 + * @tc.desc Convert class array to real array + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest4200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arrayLike = indexArrayCreateTest4200() as number[][]; + expect(Array.isArray(arrayLike[0])).assertEqual(true); + expect(arrayLike[0].toString()).assertEqual([10, 20, 30].toString()); + + expect(arrayLike[1][1]).assertEqual(20); + expect(arrayLike[0].map((item) => item * 2).toString()).assertEqual([20, 40, 60].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_4300 + * @tc.name indexArrayCreateTest4300 + * @tc.desc Add custom attributes to arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest4300', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arrayLike = indexArrayCreateTest4300(); + expect(arrayLike.length).assertEqual(3); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_4400 + * @tc.name indexArrayCreateTest4400 + * @tc.desc Array custom attribute enumeration + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest4400', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const result = indexArrayCreateTest4400(); + expect(result[0].toString()).assertEqual(['0', '1', '2', 'label'].toString()); + expect(result[1].toString()).assertEqual([10, 20, 30].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_CREATE_TEST_4500 + * @tc.name indexArrayCreateTest4500 + * @tc.desc Nested scene of array properties + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayCreateTest4500', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface BaseI{ + id: number; + tags: string[]; + } + interface BaseI1{ + users: BaseI[]; + } + const data : BaseI1 = { + users: [ + { + id: 1, + tags: ['admin', 'active'] + }, + { + id: 2, + tags: ['guest'] + } + ] + }; + expect(data.users.length).assertEqual(2); + expect(data.users[0].tags[0]).assertEqual('admin'); + data.users[0].tags[1] = 'inactive'; + expect(data.users[0].tags[1]).assertEqual('inactive'); + }); + + }); +} \ No newline at end of file diff --git a/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/indexArray/IndexArrayFill.js b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/indexArray/IndexArrayFill.js new file mode 100644 index 0000000000000000000000000000000000000000..8bcd9b31a1f99ab0c0782306a32bf7356017a94e --- /dev/null +++ b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/indexArray/IndexArrayFill.js @@ -0,0 +1,11 @@ +export function indexArrayFillTest0500(){ + const arr = [1, 2, 3]; + const result = delete arr.length; + return result; +} + +export function indexArrayFillTest0700(){ + const arr = [1, 2, 3]; + Object.freeze(arr); + return arr; +} \ No newline at end of file diff --git a/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/indexArray/IndexArrayFill.test.ets b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/indexArray/IndexArrayFill.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..e4df11b1bed589662751903d1aadeda2b8a77e18 --- /dev/null +++ b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/indexArray/IndexArrayFill.test.ets @@ -0,0 +1,603 @@ +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, TestType, Level, Size } from '@ohos/hypium'; +import { indexArrayFillTest0500, indexArrayFillTest0700 } from './IndexArrayFill'; + +function sleep(time: number): Promise { + return new Promise((re, je) => { + setTimeout(() => { + re(); + }, time); + }); +} + +export default function indexArrayFillTest() { + describe('indexArrayFillTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }) + beforeEach(async () => { + await sleep(100); + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }) + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }) + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }) + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_0100 + * @tc.name indexArrayFillTest0100 + * @tc.desc Fill in empty array index assignment + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest0100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const emp: string[] = []; + emp[0] = "Casey Jones"; + emp[1] = "Phil Lesh"; + emp[2] = "August West"; + + expect(emp.length).assertEqual(3); + expect(emp[0]).assertEqual("Casey Jones"); + expect(emp[2]).assertEqual("August West"); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_0200 + * @tc.name indexArrayFillTest0200 + * @tc.desc Non integer index assignment (attribute rather than element) + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest0200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr: string[] = []; + arr[3.4] = "Oranges"; + + expect(arr.length).assertEqual(0); + expect(arr[3.4]).assertEqual("Oranges"); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_0300 + * @tc.name indexArrayFillTest0300 + * @tc.desc Manually set the length to clear the array + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest0300', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const cats = ["Dusty", "Misty", "Twiggy"]; + cats.length = 2; + + expect(cats.length).assertEqual(2); + expect(cats).assertDeepEquals(["Dusty", "Misty"]); + expect(cats[2]).assertUndefined(); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_0400 + * @tc.name indexArrayFillTest0400 + * @tc.desc Manually set the length extension array (sparse) + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest0400', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const cats: string[] = []; + cats.length = 3; + + expect(cats.length).assertEqual(3); + expect(cats[1]).assertUndefined(); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_0500 + * @tc.name indexArrayFillTest0500 + * @tc.desc Length cannot be deleted + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + // it('indexArrayFillTest0500', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + // const result = indexArrayFillTest0500(); + // expect(result).assertEqual(false); + // }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_0600 + * @tc.name indexArrayFillTest0600 + * @tc.desc Non integer length error + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest0600', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, 2, 3]; + + expect(() => { + arr.length = 2.5; + }).assertThrowError(RangeError); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_0700 + * @tc.name indexArrayFillTest0700 + * @tc.desc The length of the frozen array cannot be modified + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest0700', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = indexArrayFillTest0700(); + + expect(() => { + arr.length = 2; + }).assertThrowError(TypeError); + expect(arr.length).assertEqual(3); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_0800 + * @tc.name indexArrayFillTest0800 + * @tc.desc The linkage between length and array methods + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest0800', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, 2]; + + arr.push(3); + expect(arr.length).assertEqual(3); + + arr.pop(); + expect(arr.length).assertEqual(2); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_0900 + * @tc.name indexArrayFillTest0900 + * @tc.desc For Loop Traverse Array (Based on Length) + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest0900', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const colors = ["red", "green", "blue"]; + const result: string[] = []; + + for (let i = 0; i < colors.length; i++) { + result.push(colors[i]); + } + + expect(result).assertDeepEquals(["red", "green", "blue"]); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_1000 + * @tc.name indexArrayFillTest1000 + * @tc.desc For loop traversal of non false element arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest1000', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, 2, 3]; + const result: number[] = []; + let i = 0, item = 0; + + while ((item = arr[i])) { + result.push(item); + i++; + } + expect(result).assertDeepEquals([1, 2, 3]); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_1100 + * @tc.name indexArrayFillTest1100 + * @tc.desc ForEach traverses a regular array + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest1100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const colors = ["red", "green", "blue"]; + const result: string[] = []; + + colors.forEach((color) => { + result.push(color); + }); + + expect(result).assertDeepEquals(["red", "green", "blue"]); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_1200 + * @tc.name indexArrayFillTest1200 + * @tc.desc ForEach skips empty elements in sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest1200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const sparseArray = ["first", "second", , "fourth"]; + const result: string[] = []; + + sparseArray.forEach((element) => { + result.push(element as string); + }); + + expect(result).assertDeepEquals(["first", "second", "fourth"]); + expect(sparseArray[2]).assertUndefined(); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_1300 + * @tc.name indexArrayFillTest1300 + * @tc.desc ForEach Traverse Non Sparse Arrays Containing Undefined + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest1300', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const nonsparseArray = ["first", "second", undefined, "fourth"]; + const result: (string | undefined)[] = []; + + nonsparseArray.forEach((element) => { + result.push(element); + }); + expect(result).assertDeepEquals(["first", "second", undefined, "fourth"]); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_1400 + * @tc.name indexArrayFillTest1400 + * @tc.desc For... of Traversing an Array + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest1400', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, 2, 3]; + const result: number[] = []; + + for (const item of arr) { + result.push(item); + } + expect(result).assertDeepEquals([1, 2, 3]); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_1500 + * @tc.name indexArrayFillTest1500 + * @tc.desc Traverse an empty array + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest1500', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr: number[] = []; + let forCount = 0; + let forEachCount = 0; + + for (let i = 0; i < arr.length; i++) { + forCount++; + } + + arr.forEach(() => { + forEachCount++; + }); + expect(forCount).assertEqual(0); + expect(forEachCount).assertEqual(0); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_1600 + * @tc.name indexArrayFillTest1600 + * @tc.desc Traverse nested arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest1600', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const nestedArr = [[1, 2], [3, 4], [5, 6]]; + const result: number[] = []; + + for (let i = 0; i < nestedArr.length; i++) { + for (let j = 0; j < nestedArr[i].length; j++) { + result.push(nestedArr[i][j]); + } + } + expect(result.toString()).assertEqual([1, 2, 3, 4, 5, 6].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_1700 + * @tc.name indexArrayFillTest1700 + * @tc.desc Concat() connects arrays and elements + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest1700', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + let myArray = ["1", "2", "3"]; + myArray = myArray.concat("a", "b", "c"); + + expect(myArray.toString()).assertEqual(["1", "2", "3", "a", "b", "c"].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_1800 + * @tc.name indexArrayFillTest1800 + * @tc.desc join() connects arrays and elements + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest1800', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const myArray = ["Wind", "Rain", "Fire"]; + const list = myArray.join(" - "); + + expect(list).assertEqual("Wind - Rain - Fire"); + expect(myArray.join()).assertEqual("Wind,Rain,Fire"); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_1900 + * @tc.name indexArrayFillTest1900 + * @tc.desc Shift() removes the starting element + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest1900', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const myArray = ["1", "2", "3"]; + const first = myArray.shift(); + + expect(myArray.toString()).assertEqual(["2", "3"].toString()); + expect(first).assertEqual("1"); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_2000 + * @tc.name indexArrayFillTest2000 + * @tc.desc Add elements starting with unshhift() + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest2000', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const myArray = ["1", "2", "3"]; + const newLength = myArray.unshift("4", "5"); + + expect(myArray.toString()).assertEqual(["4", "5", "1", "2", "3"].toString()); + expect(newLength).assertEqual(5); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_2100 + * @tc.name indexArrayFillTest2100 + * @tc.desc Slice() extracts array fragments + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest2100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + let myArray = ["a", "b", "c", "d", "e"]; + myArray = myArray.slice(1, 4); + + expect(myArray.toString()).assertEqual(["b", "c", "d"].toString()); + expect(myArray.slice(-2).toString()).assertEqual(["c", "d"].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_2200 + * @tc.name indexArrayFillTest2200 + * @tc.desc Splice() removes and replaces elements + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest2200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const myArray = ["1", "2", "3", "4", "5"]; + const deleted = myArray.splice(1, 3, "a", "b", "c", "d"); + + expect(myArray.toString()).assertEqual(["1", "a", "b", "c", "d", "5"].toString()); + expect(deleted.toString()).assertEqual(["2", "3", "4"].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_2300 + * @tc.name indexArrayFillTest2300 + * @tc.desc Reverse() reverses the order of the array + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest2300', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const myArray = ["1", "2", "3"]; + const reversed = myArray.reverse(); + + expect(myArray.toString()).assertEqual(["3", "2", "1"].toString()); + expect(reversed).assertEqual(myArray); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_2400 + * @tc.name indexArrayFillTest2400 + * @tc.desc Flat() flattens the array + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest2400', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + let myArray = [1, 2, [3, 4, [5, 6]]]; + + expect(myArray.flat().toString()).assertEqual([1, 2, 3, 4, [5, 6]].toString()); + expect(myArray.flat(2).toString()).assertEqual([1, 2, 3, 4, 5, 6].toString()); + expect(myArray.flat(Infinity).toString()).assertEqual([1, 2, 3, 4, 5, 6].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_2500 + * @tc.name indexArrayFillTest2500 + * @tc.desc Sort() default sorting + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest2500', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const myArray = ["Wind", "Rain", "Fire"]; + const sorted = myArray.sort(); + + expect(myArray.toString()).assertEqual(["Fire", "Rain", "Wind"].toString()); + expect(sorted).assertEqual(myArray); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_2600 + * @tc.name indexArrayFillTest2600 + * @tc.desc Sort() custom sorting (by last character) + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest2600', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const myArray = ["Wind", "Rain", "Fire"]; + const sortFn = (a: string, b: string) => { + if (a[a.length - 1] < b[b.length - 1]) return -1; + if (a[a.length - 1] > b[b.length - 1]) return 1; + return 0; + }; + myArray.sort(sortFn); + expect(myArray.toString()).assertEqual(["Wind", "Fire", "Rain"].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_2700 + * @tc.name indexArrayFillTest2700 + * @tc.desc IndexOf() searches for the first appearance position of an element + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest2700', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const a = ["a", "b", "a", "b", "a"]; + + expect(a.indexOf("b")).assertEqual(1); + expect(a.indexOf("b", 2)).assertEqual(3); + expect(a.indexOf("z")).assertEqual(-1); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_2800 + * @tc.name indexArrayFillTest2800 + * @tc.desc LastIndexOf() searches for the last appearance position of an element + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest2800', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const a = ["a", "b", "c", "d", "a", "b"]; + + expect(a.lastIndexOf("b")).assertEqual(5); + expect(a.lastIndexOf("b", 4)).assertEqual(1); + expect(a.lastIndexOf("z")).assertEqual(-1); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_2900 + * @tc.name indexArrayFillTest2900 + * @tc.desc Map() maps array elements + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest2900', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const a1 = ["a", "b", "c"]; + const a2 = a1.map((item) => item.toUpperCase()); + + expect(a2.toString()).assertEqual(["A", "B", "C"].toString()); + expect(a1.toString()).assertEqual(["a", "b", "c"].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_3000 + * @tc.name indexArrayFillTest3000 + * @tc.desc Filter() filters array elements + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest3000', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const a1 = ["a", 10, "b", 20, "c", 30]; + const a2 = a1.filter((item) => typeof item === "number"); + + expect(a2.toString()).assertEqual([10, 20, 30].toString()); + expect(a1.toString()).assertEqual(["a", 10, "b", 20, "c", 30].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_3100 + * @tc.name indexArrayFillTest3100 + * @tc.desc Reduce() accumulates array elements + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest3100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const a = [10, 20, 30]; + const total = a.reduce((acc, curr) => acc + curr, 0); + + expect(total).assertEqual(60); + + const total2 = [10, 20, 30].reduce((acc, curr) => acc + curr); + expect(total2).assertEqual(60); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_3200 + * @tc.name indexArrayFillTest3200 + * @tc.desc Every () verifies that all elements meet the conditions + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest3200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const isNumber = (value: number | string) => typeof value === "number"; + const a1 = [1, 2, 3]; + const a2 = [1, "2", 3]; + + expect(a1.every(isNumber)).assertEqual(true); + expect(a2.every(isNumber)).assertEqual(false); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_FILL_TEST_3300 + * @tc.name indexArrayFillTest3300 + * @tc.desc Some() verifies the existence of elements that meet the conditions + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayFillTest3300', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const isNumber = (value: number | string) => typeof value === "number"; + const a1 = [1, 2, 3]; + const a2 = ["1", "2", "3"]; + + expect(a1.some(isNumber)).assertEqual(true); + expect(a2.some(isNumber)).assertEqual(false); + }); + + }); +} \ No newline at end of file diff --git a/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/indexArray/IndexArrayMulArr.test.ets b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/indexArray/IndexArrayMulArr.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..20fa6124369b0e55af2f3c63e28995e48fa54317 --- /dev/null +++ b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/indexArray/IndexArrayMulArr.test.ets @@ -0,0 +1,498 @@ +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, TestType, Level, Size } from '@ohos/hypium'; + +function sleep(time: number): Promise { + return new Promise((re, je) => { + setTimeout(() => { + re(); + }, time); + }); +} +export default function indexArrayMulArrTest() { + describe('indexArrayMulArrTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }) + beforeEach(async () => { + await sleep(100); + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }) + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }) + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }) + /** + * @tc.number SUB_INDEX_ARRAY_MUL_ARR_TEST_0100 + * @tc.name indexArrayMulArrTest0100 + * @tc.desc Nested for loop to create 2D array + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayMulArrTest0100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const a = new Array(4); + for (let i = 0; i < 4; i++) { + a[i] = new Array(4); + for (let j = 0; j < 4; j++) { + a[i][j] = `[${i},${j}]`; + } + } + + expect(a.length).assertEqual(4); + expect(a[0].length).assertEqual(4); + expect(a[0][0]).assertEqual('[0,0]'); + expect(a[3][3]).assertEqual('[3,3]'); + expect(a[2][1]).assertEqual('[2,1]'); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_MUL_ARR_TEST_0200 + * @tc.name indexArrayMulArrTest0200 + * @tc.desc Create a 2D array using Array.from + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayMulArrTest0200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const twoDArr = Array.from({ length: 2 } as ArrayLike, () => Array.from({ length: 3 } as ArrayLike, () => 0)); + + expect(twoDArr.length).assertEqual(2); + expect(twoDArr[0].length).assertEqual(3); + expect(twoDArr[0][0]).assertEqual(0); + expect(twoDArr[1][2]).assertEqual(0); + + twoDArr[0][1] = 5; + expect(twoDArr[0][1]).assertEqual(5); + expect(twoDArr[1][1]).assertEqual(0); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_MUL_ARR_TEST_0300 + * @tc.name indexArrayMulArrTest0300 + * @tc.desc Create a 3D array + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayMulArrTest0300', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const threeDArr = [ + [ + [1, 2], + [3, 4] + ], + [ + [5, 6], + [7, 8] + ] + ]; + + expect(threeDArr.length).assertEqual(2); + expect(threeDArr[0].length).assertEqual(2); + expect(threeDArr[0][0].length).assertEqual(2); + expect(threeDArr[1][0][1]).assertEqual(6); + expect(threeDArr[0][1][0]).assertEqual(3); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_MUL_ARR_TEST_0400 + * @tc.name indexArrayMulArrTest0400 + * @tc.desc Create irregular multidimensional arrays (jagged arrays) + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayMulArrTest0400', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const jaggedArr = [ + [1, 2, 3], + [4], + [5, 6] + ]; + + expect(jaggedArr.length).assertEqual(3); + expect(jaggedArr[0].length).assertEqual(3); + expect(jaggedArr[1].length).assertEqual(1); + expect(jaggedArr[2].length).assertEqual(2); + expect(jaggedArr[1][0]).assertEqual(4); + expect(jaggedArr[2][1]).assertEqual(6); + expect(jaggedArr[0][2]).assertEqual(3); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_MUL_ARR_TEST_0500 + * @tc.name indexArrayMulArrTest0500 + * @tc.desc 2D array element access + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayMulArrTest0500', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const twoDArr = [ + [100, 200, 300], + [400, 500, 600], + [700, 800, 900] + ]; + + expect(twoDArr[0][0]).assertEqual(100); + expect(twoDArr[1][2]).assertEqual(600); + expect(twoDArr[2][1]).assertEqual(800); + + expect(twoDArr[3]).assertUndefined(); + expect(twoDArr[0][5]).assertUndefined(); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_MUL_ARR_TEST_0600 + * @tc.name indexArrayMulArrTest0600 + * @tc.desc Modification of two-dimensional array elements + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayMulArrTest0600', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const twoDArr = [ + [1, 2], + [3, 4] + ]; + + twoDArr[0][1] = 20; + expect(twoDArr[0][1]).assertEqual(20); + + twoDArr[1] = [30, 40]; + expect(twoDArr[1][0]).assertEqual(30); + expect(twoDArr[1][1]).assertEqual(40); + + twoDArr[2] = [5, 6]; + expect(twoDArr.length).assertEqual(3); + expect(twoDArr[2][0]).assertEqual(5); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_MUL_ARR_TEST_0700 + * @tc.name indexArrayMulArrTest0700 + * @tc.desc Access and modification of three-dimensional array elements + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayMulArrTest0700', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const threeDArr = [ + [ + [1, 2], + [3, 4] + ], + [ + [5, 6], + [7, 8] + ] + ]; + + expect(threeDArr[0][1][0]).assertEqual(3); + expect(threeDArr[1][0][1]).assertEqual(6); + + threeDArr[1][1][1] = 80; + expect(threeDArr[1][1][1]).assertEqual(80); + + threeDArr[0][0] = [10, 20]; + expect(threeDArr[0][0][0]).assertEqual(10); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_MUL_ARR_TEST_0800 + * @tc.name indexArrayMulArrTest0800 + * @tc.desc Dynamically add multidimensional array elements + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayMulArrTest0800', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const twoDArr = [ + [1, 2], + [3, 4] + ]; + + twoDArr[0].push(5); + expect(twoDArr[0].length).assertEqual(3); + expect(twoDArr[0][2]).assertEqual(5); + + twoDArr.push([6, 7, 8]); + expect(twoDArr.length).assertEqual(3); + expect(twoDArr[2][1]).assertEqual(7); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_MUL_ARR_TEST_0900 + * @tc.name indexArrayMulArrTest0900 + * @tc.desc Dynamically add multidimensional array elements + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayMulArrTest0900', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const twoDArr = [ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9] + ]; + + twoDArr[0].splice(1, 1); + expect(twoDArr[0]).assertDeepEquals([1, 3]); + expect(twoDArr[0].length).assertEqual(2); + + twoDArr.splice(1, 1); + expect(twoDArr.length).assertEqual(2); + expect(twoDArr[1]).assertDeepEquals([7, 8, 9]); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_MUL_ARR_TEST_1000 + * @tc.name indexArrayMulArrTest1000 + * @tc.desc Nested for loop traversal of two-dimensional array + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayMulArrTest1000', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const twoDArr = [ + [1, 2], + [3, 4], + [5, 6] + ]; + const allElements : number[] = []; + + for (let i = 0; i < twoDArr.length; i++) { + for (let j = 0; j < twoDArr[i].length; j++) { + allElements.push(twoDArr[i][j]); + } + } + expect(allElements).assertDeepEquals([1, 2, 3, 4, 5, 6]); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_MUL_ARR_TEST_1100 + * @tc.name indexArrayMulArrTest1100 + * @tc.desc For... of Loop Traversing a 2D Array + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayMulArrTest1100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const twoDArr = [ + ['a', 'b'], + ['c', 'd'] + ]; + const allElements : string[] = []; + + for (const row of twoDArr) { + for (const item of row) { + allElements.push(item); + } + } + expect(allElements).assertDeepEquals(['a', 'b', 'c', 'd']); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_MUL_ARR_TEST_1200 + * @tc.name indexArrayMulArrTest1200 + * @tc.desc Verify traversing a two-dimensional array through forEach + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayMulArrTest1200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const twoDArr = [ + [10, 20], + [30, 40] + ]; + const allElements : number[] = []; + + twoDArr.forEach(row => { + row.forEach(item => { + allElements.push(item); + }); + }); + expect(allElements).assertDeepEquals([10, 20, 30, 40]); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_MUL_ARR_TEST_1300 + * @tc.name indexArrayMulArrTest1300 + * @tc.desc Traverse 3D arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayMulArrTest1300', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const threeDArr = [ + [ + [1, 2], + [3, 4] + ], + [ + [5, 6], + [7, 8] + ] + ]; + const allElements : number[] = []; + + for (const layer1 of threeDArr) { + for (const layer2 of layer1) { + for (const item of layer2) { + allElements.push(item); + } + } + } + expect(allElements).assertDeepEquals([1, 2, 3, 4, 5, 6, 7, 8]); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_MUL_ARR_TEST_1400 + * @tc.name indexArrayMulArrTest1400 + * @tc.desc Irregular two-dimensional array traversal + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayMulArrTest1400', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const jaggedArr = [ + [1, 2, 3], + [4], + [5, 6] + ]; + const allElements : number[] = []; + + jaggedArr.forEach(row => { + row.forEach(item => { + allElements.push(item); + }); + }); + expect(allElements).assertDeepEquals([1, 2, 3, 4, 5, 6]); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_MUL_ARR_TEST_1500 + * @tc.name indexArrayMulArrTest1500 + * @tc.desc Flattening two-dimensional arrays (flat method) + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayMulArrTest1500', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const twoDArr = [ + [1, 2], + [3, 4], + [5, 6] + ]; + + const flattened = twoDArr.flat(1); + expect(flattened).assertDeepEquals([1, 2, 3, 4, 5, 6]); + expect(Array.isArray(flattened)).assertEqual(true); + + const jaggedArr = [1, [2, [3, 4]]]; + const flatDeep = jaggedArr.flat(Infinity); + expect(flatDeep).assertDeepEquals([1, 2, 3, 4]); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_MUL_ARR_TEST_1600 + * @tc.name indexArrayMulArrTest1600 + * @tc.desc 2D array mapping (map method) + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayMulArrTest1600', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const twoDArr = [ + [1, 2], + [3, 4] + ]; + + const mapped = twoDArr.map(row => row.map(item => item * 2)); + expect(mapped).assertDeepEquals([[2, 4], [6, 8]]); + + const rowMapped = twoDArr.map(row => [row[0] + row[1]]); + expect(rowMapped).assertDeepEquals([[3], [7]]); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_MUL_ARR_TEST_1700 + * @tc.name indexArrayMulArrTest1700 + * @tc.desc 2D array filtering (filter method) + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayMulArrTest1700', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const twoDArr = [ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9] + ]; + + const rowFiltered = twoDArr.filter(row => row[0] > 3); + expect(rowFiltered).assertDeepEquals([[4, 5, 6], [7, 8, 9]]); + + const itemFiltered = twoDArr.flat().filter(item => item > 5); + expect(itemFiltered).assertDeepEquals([6, 7, 8, 9]); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_MUL_ARR_TEST_1800 + * @tc.name indexArrayMulArrTest1800 + * @tc.desc Sum two-dimensional arrays (reduce method) + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayMulArrTest1800', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const twoDArr = [ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9] + ]; + + const sum1 = twoDArr.flat().reduce((acc, val) => acc + val, 0); + expect(sum1).assertEqual(45); + + const sum2 = twoDArr.reduce((rowAcc, row) => { + return rowAcc + row.reduce((itemAcc, item) => itemAcc + item, 0); + }, 0); + expect(sum2).assertEqual(45); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_MUL_ARR_TEST_1900 + * @tc.name indexArrayMulArrTest1900 + * @tc.desc Multi dimensional array JSON serialization and parsing + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArrayMulArrTest1900', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const twoDArr = [ + [1, 2], + [3, 4] + ]; + + const jsonStr = JSON.stringify(twoDArr); + expect(jsonStr).assertEqual('[[1,2],[3,4]]'); + + const parsedArr = JSON.parse(jsonStr) as number[][]; + expect(parsedArr).assertDeepEquals(twoDArr); + expect(Array.isArray(parsedArr)).assertEqual(true); + expect(Array.isArray(parsedArr[0])).assertEqual(true); + + parsedArr[0][0] = 100; + expect(parsedArr[0][0]).assertEqual(100); + expect(twoDArr[0][0]).assertEqual(1); + }); + + }); +} \ No newline at end of file diff --git a/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/indexArray/IndexArraySparse.js b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/indexArray/IndexArraySparse.js new file mode 100644 index 0000000000000000000000000000000000000000..a2d7085d84d5cbb4b938336d3625982aa311faa5 --- /dev/null +++ b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/indexArray/IndexArraySparse.js @@ -0,0 +1,8 @@ +export function indexArraySparseTest1000(){ + const arr = [1, , 3, , 5]; + const keys = []; + for (const key in arr) { + keys.push(key); + } + return keys; +} \ No newline at end of file diff --git a/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/indexArray/IndexArraySparse.test.ets b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/indexArray/IndexArraySparse.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..9b39ac8a508b2e92dcd949cdb7015aedf67503f5 --- /dev/null +++ b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/indexArray/IndexArraySparse.test.ets @@ -0,0 +1,738 @@ +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, TestType, Level, Size } from '@ohos/hypium'; +import { indexArraySparseTest1000 } from './IndexArraySparse'; + +function sleep(time: number): Promise { + return new Promise((re, je) => { + setTimeout(() => { + re(); + }, time); + }); +} + +export default function indexArraySparseTest() { + describe('indexArraySparseTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }) + beforeEach(async () => { + await sleep(100); + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }) + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }) + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }) + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_0100 + * @tc.name indexArraySparseTest0100 + * @tc.desc Array constructor creates an empty array of specified length + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest0100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = new Array(5); + expect(arr.length).assertEqual(5); + expect(arr[0]).assertUndefined(); + expect(Object.keys(arr)).not().assertContain(0); + expect(Object.keys(arr)).assertDeepEquals([]); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_0200 + * @tc.name indexArraySparseTest0200 + * @tc.desc Create empty slots with consecutive commas for array literals + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest0200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, 2, , , 5]; + expect(arr.length).assertEqual(5); + expect(arr[0]).assertEqual(1); + expect(arr[2]).assertUndefined(); + expect(Object.keys(arr)).not().assertContain(2); + expect(Object.keys(arr)).assertContain(4); + expect(Object.keys(arr)).assertDeepEquals(['0', '1', '4']); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_0300 + * @tc.name indexArraySparseTest0300 + * @tc.desc Index out of bounds assignment creates empty slot + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest0300', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, 2]; + arr[4] = 5; + expect(arr.length).assertEqual(5); + expect(arr[2]).assertUndefined(); + expect(Object.keys(arr)).not().assertContain(3); + expect(arr[4]).assertEqual(5); + expect(Object.keys(arr)).assertDeepEquals(['0', '1', '4']); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_0400 + * @tc.name indexArraySparseTest0400 + * @tc.desc Modify the length property to create an empty slot + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest0400', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, 2]; + arr.length = 5; + expect(arr.length).assertEqual(5); + expect(arr[3]).assertUndefined(); + expect(Object.keys(arr)).not().assertContain(2); + expect(arr[0]).assertEqual(1); + expect(Object.keys(arr)).assertDeepEquals(['0', '1']); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_0500 + * @tc.name indexArraySparseTest0500 + * @tc.desc The difference between sparse arrays and undefined filled arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest0500', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const sparse = [1, , 3]; + const dense = [1, undefined, 3]; + + expect(sparse[1]).assertUndefined(); + expect(dense[1]).assertUndefined(); + + expect(Object.keys(sparse)).not().assertContain(1); + expect(Object.keys(dense)).assertContain(1); + + expect(Object.keys(sparse)).assertDeepEquals(['0', '2']); + expect(Object.keys(dense)).assertDeepEquals(['0', '1', '2']); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_0600 + * @tc.name indexArraySparseTest0600 + * @tc.desc Validation of creating ultra long sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest0600', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const largeSparse = new Array(100000); + largeSparse[99999] = 'end'; + + expect(largeSparse.length).assertEqual(100000); + expect(largeSparse[0]).assertUndefined(); + expect(Object.keys(largeSparse)).not().assertContain(0); + expect(largeSparse[99999]).assertEqual('end'); + expect(Object.keys(largeSparse)).assertContain(99999); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_0700 + * @tc.name indexArraySparseTest0700 + * @tc.desc For... of Loop Iteration Sparse Array + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest0700', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3, , 5]; + const result: number[] = []; + for (const item of arr) { + result.push(item as number); + } + expect(Object.keys(result).toString()).assertEqual(['0', '1', '2', '3', '4'].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_0800 + * @tc.name indexArraySparseTest0800 + * @tc.desc Array expansion operation processing for sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest0800', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3]; + const spread = [...arr]; + expect(spread.toString()).assertEqual([1, undefined, 3].toString()); + expect(Object.keys(spread)).assertContain(1); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_0900 + * @tc.name indexArraySparseTest0900 + * @tc.desc Array.from handles sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest0900', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3]; + const fromArr = Array.from(arr); + expect(fromArr.toString()).assertEqual([1, undefined, 3].toString()); + expect(Object.keys(fromArr)).assertContain(1); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_1000 + * @tc.name indexArraySparseTest1000 + * @tc.desc For... in Loop Iteration Sparse Array + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest1000', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const keys = indexArraySparseTest1000(); + expect(keys.toString()).assertEqual(['0', '2', '4'].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_1100 + * @tc.name indexArraySparseTest1100 + * @tc.desc Object. keys gets sparse array key names + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest1100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [, 2, , 4,]; + expect(Object.keys(arr).toString()).assertEqual(['1', '3'].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_1200 + * @tc.name indexArraySparseTest1200 + * @tc.desc Array index traversal (for loop) + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest1200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3]; + const values: (number | undefined)[] = []; + for (let i = 0; i < arr.length; i++) { + values.push(arr[i]); + } + expect(Object.keys(values).toString()).assertEqual(['0', '1', '2'].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_1300 + * @tc.name indexArraySparseTest1300 + * @tc.desc In operator detects empty slots + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest1300', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, undefined, , 4]; + expect(Object.keys(arr)).assertContain(0) + expect(Object.keys(arr)).assertContain(1) + expect(Object.keys(arr)).not().assertContain(2) + expect(Object.keys(arr)).assertContain(3) + expect(Object.keys(arr)).not().assertContain(4) + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_1400 + * @tc.name indexArraySparseTest1400 + * @tc.desc Arrays. prototype. includes handle sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest1400', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3]; + expect(arr.includes(undefined)).assertEqual(true); + expect(arr.includes(1)).assertEqual(true); + expect(arr.includes(2)).assertEqual(false); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_1500 + * @tc.name indexArraySparseTest1500 + * @tc.desc IndexOf searches for undefined and empty slots + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest1500', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [undefined, , 3]; + expect(arr.indexOf(undefined)).assertEqual(0); + expect(arr.indexOf(undefined, 1)).assertEqual(-1); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_1600 + * @tc.name indexArraySparseTest1600 + * @tc.desc Map method for handling sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest1600', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3]; + const mapped = arr.map(x => x? x * 2 : x); + expect(mapped.toString()).assertEqual([2, , 6].toString()); + expect(Object.keys(mapped)).not().assertContain(1) + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_1700 + * @tc.name indexArraySparseTest1700 + * @tc.desc The forEach method handles sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest1700', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3, , 5]; + const logs: (number | undefined)[] = []; + arr.forEach(x => logs.push(x)); + expect(logs.toString()).assertEqual([1, 3, 5].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_1800 + * @tc.name indexArraySparseTest1800 + * @tc.desc The filter method handles sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest1800', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3, , 5]; + const filtered = arr.filter(() => true); + expect(filtered.toString()).assertEqual([1, 3, 5].toString()); + expect(filtered.length).assertEqual(3); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_1900 + * @tc.name indexArraySparseTest1900 + * @tc.desc Every method deals with sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest1900', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr1 = [2, , 4]; + expect(arr1.every(x => x? x > 1 : false)).assertEqual(true); + + const arr2 = [2, , 0]; + expect(arr2.every(x => x? x > 1 : false)).assertEqual(false); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_2000 + * @tc.name indexArraySparseTest2000 + * @tc.desc Some method for handling sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest2000', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr1 = [1, , 3]; + expect(arr1.some(x => x? x * 2 : x)).assertEqual(true); + + const arr2 = [1, , 2]; + expect(arr2.some(x => x? x * 2 : x)).assertEqual(true); + + const arr3 = [, ,]; + expect(arr3.some(() => true)).assertEqual(false); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_2100 + * @tc.name indexArraySparseTest2100 + * @tc.desc Find method for handling sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest2100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3, , 5]; + const found = arr.find(x => x? x * 2 : x); + expect(found).assertEqual(1); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_2200 + * @tc.name indexArraySparseTest2200 + * @tc.desc FindIndex method for handling sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest2200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3, , 5]; + const index = arr.findIndex(x => x? x > 2 : false); + expect(index).assertEqual(2); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_2300 + * @tc.name indexArraySparseTest2300 + * @tc.desc The fill method handles sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest2300', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3]; + arr.fill(0); + expect(arr.toString()).assertEqual([0, 0, 0].toString()); + expect(Object.keys(arr)).assertContain(1); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_2400 + * @tc.name indexArraySparseTest2400 + * @tc.desc Join method for handling sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest2400', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3]; + expect(arr.join(',')).assertEqual('1,,3'); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_2500 + * @tc.name indexArraySparseTest2500 + * @tc.desc Concat method for handling sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest2500', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr1 = [1, , 3]; + const arr2 = [4, , 6]; + const concatenated = arr1.concat(arr2); + + expect(concatenated.length).assertEqual(6); + expect(concatenated.toString()).assertEqual([1, , 3, 4, , 6].toString()); + + expect(Object.keys(concatenated)).not().assertContain(1); + expect(Object.keys(concatenated)).assertContain(5); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_2600 + * @tc.name indexArraySparseTest2600 + * @tc.desc Slice method for handling sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest2600', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3, , 5]; + const sliced = arr.slice(1, 4); + + expect(sliced.toString()).assertEqual([, 3, ,].toString()); + expect(sliced.length).assertEqual(3); + expect(Object.keys(sliced)).not().assertContain(0); + expect(Object.keys(sliced)).assertContain(1); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_2700 + * @tc.name indexArraySparseTest2700 + * @tc.desc flat method for handling sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest2700', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, [, 3], , 5]; + const flattened = arr.flat(); + + expect(flattened.toString()).assertEqual([1, 3, 5].toString()); + expect(Object.keys(flattened)).assertContain(1); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_2800 + * @tc.name indexArraySparseTest2800 + * @tc.desc sort method for handling sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest2800', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [3, , 1, , 2]; + arr.sort((a, b) => { + if (a) { + if (b) { + return a - b; + } + return 1; + } + return 1; + }); + + expect(arr.toString()).assertEqual([1, 2, 3, , ,].toString()); + expect(Object.keys(arr)).not().assertContain(3); + expect(Object.keys(arr)).not().assertContain(4); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_2900 + * @tc.name indexArraySparseTest2900 + * @tc.desc reverse method for handling sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest2900', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3, , 5]; + arr.reverse(); + + expect(arr.toString()).assertEqual([5, , 3, , 1].toString()); + expect(Object.keys(arr)).not().assertContain(1); + expect(Object.keys(arr)).not().assertContain(3); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_3000 + * @tc.name indexArraySparseTest3000 + * @tc.desc JSON.stringify method for handling sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest3000', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3]; + const json = JSON.stringify(arr); + expect(json).assertEqual('[1,null,3]'); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_3100 + * @tc.name indexArraySparseTest3100 + * @tc.desc JSON. parse restores sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest3100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const json = '[1,null,3]'; + const arr = JSON.parse(json) as (number | null)[]; + + expect(arr.toString()).assertEqual([1, null, 3].toString()); + expect(Object.keys(arr)).assertContain(1); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_3200 + * @tc.name indexArraySparseTest3200 + * @tc.desc toLocaleString method for handling sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest3200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3, , 5]; + expect(arr.toString()).assertEqual('1,,3,,5'); + expect(arr.toLocaleString()).assertEqual('1,,3,,5'); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_3300 + * @tc.name indexArraySparseTest3300 + * @tc.desc Arrays. prototype. values iterators + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest3300', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3]; + const values = Array.from(arr.values()); + expect(values.toString()).assertEqual([1, undefined, 3].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_3400 + * @tc.name indexArraySparseTest3400 + * @tc.desc Sparse array and Set conversion + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest3400', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3]; + const set = new Set(arr); + expect(Array.from(set).toString()).assertEqual([1, undefined, 3].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_3500 + * @tc.name indexArraySparseTest3500 + * @tc.desc Sparse array copying (slice and concat) + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest3500', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3]; + + const copy1 = arr.slice(); + expect(copy1.toString()).assertEqual([1, , 3].toString()); + expect(Object.keys(copy1)).not().assertContain(1); + + const copy2 = ([] as (number | undefined)[]).concat(arr); + expect(copy2.toString()).assertEqual([1, , 3].toString()); + expect(Object.keys(copy2)).not().assertContain(1); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_3600 + * @tc.name indexArraySparseTest3600 + * @tc.desc Populate sparse array and serialize it + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest3600', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = new Array(3); + arr.fill(2); + expect(JSON.stringify(arr)).assertEqual('[2,2,2]'); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_3700 + * @tc.name indexArraySparseTest3700 + * @tc.desc Sparse array to Map + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest3700', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3]; + const map = new Map(Array.from(arr.entries())); + expect(Array.from(map).toString()).assertEqual([[0, 1], [1, ,], [2, 3]].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_3800 + * @tc.name indexArraySparseTest3800 + * @tc.desc Entries iterators for sparse arrays + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest3800', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3]; + const entries = Array.from(arr.entries()); + expect(entries.toString()).assertEqual([[0, 1], [1, ,], [2, 3]].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_3900 + * @tc.name indexArraySparseTest3900 + * @tc.desc Behavior of sparse array after adding elements + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest3900', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3]; + expect(Object.keys(arr)).not().assertContain(1); + + arr[1] = 2; + expect(arr.toString()).assertEqual([1, 2, 3].toString()); + expect(Object.keys(arr)).assertContain(1); + expect(arr.map(x => x? x * 2 : x).toString()).assertEqual([2, 4, 6].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_4000 + * @tc.name indexArraySparseTest4000 + * @tc.desc Nested Sparse Array Processing + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest4000', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const nested = [1, , [3, , 5]]; + + const mapped = nested.map(item => + Array.isArray(item) ? item.map(x => x? x * 2 : x) : item? item * 2 : item + ); + expect(mapped.toString()).assertEqual([2, , [6, , 10]].toString()); + + const flattened = nested.flat(Infinity); + expect(flattened.toString()).assertEqual([1, 3, 5].toString()); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_4100 + * @tc.name indexArraySparseTest4100 + * @tc.desc Sparse arrays and function parameters + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest4100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const arr = [1, , 3]; + + const result = logArgs(...arr); + expect(result.toString()).assertEqual([1, undefined, 3].toString()); + expect(Object.keys(result)).assertContain(1); + }); + + /** + * @tc.number SUB_INDEX_ARRAY_SPARSE_TEST_4200 + * @tc.name indexArraySparseTest4200 + * @tc.desc Sparse array performance test (compared to dense arrays) + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('indexArraySparseTest4200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const sparse = new Array(1000000); + for (let i = 0; i < 10; i++) { + sparse[i * 100000] = i; + } + + const dense = new Array(1000000).fill(0); + + expect(Object.keys(sparse).length).assertEqual(10); + expect(Object.keys(dense).length).assertEqual(1000000); + + let sparseTime = 0; + const startSparse = new Date().getTime(); + sparse.forEach(() => {}); + sparseTime = new Date().getTime() - startSparse; + + let denseTime = 0; + const startDense = new Date().getTime(); + dense.forEach(() => {}); + denseTime = new Date().getTime() - startDense; + + expect(sparseTime).assertLess(denseTime); + }); + + }); +} + +function logArgs(...args : (number | undefined)[]) { + return args; +} \ No newline at end of file diff --git a/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectAllProp.js b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectAllProp.js new file mode 100644 index 0000000000000000000000000000000000000000..9487790fc5b0f484fa793ccf19abf6b614433387 --- /dev/null +++ b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectAllProp.js @@ -0,0 +1,361 @@ +function listAllProperties(o) { + let objectToInspect; + const result = []; + + for ( + objectToInspect = o; + objectToInspect !== null; + objectToInspect = Object.getPrototypeOf(objectToInspect) + ) { + result.push(...Object.getOwnPropertyNames(objectToInspect)); + } + + return result; +} + +function uniqueArray(arr) { + return [...new Set(arr)]; +} + +const baseProto = { baseProp: 'base', baseMethod() {} }; +const subProto = Object.create(baseProto); +subProto.subProp = 'sub'; +Object.defineProperty(subProto, 'subNonEnum', { + value: 'sub non-enumerable', + enumerable: false +}); + +class BaseClass { + baseClassProp = 'base class'; + baseClassMethod() {} +} + +class SubClass extends BaseClass { + subClassProp = 'sub class'; + subClassMethod() {} +} + +export function objectSetProto(){ + const obj = { a: 1 }; + const proto = { b: 2 }; + Object.setPrototypeOf(obj, proto); + return obj; +} + +export function objectAllPropTest0100(){ + const obj = objectSetProto(); + + const enumerated = []; + for (const prop in obj) { + enumerated.push(prop); + } + return enumerated; +} + +export function objectAllPropTest0300(){ + const obj = { a: 1 }; + Object.defineProperty(obj, 'b', { + value: 2, + enumerable: false + }); + + return obj; +} + +export function objectAllPropTest0400(){ + const obj = {}; + obj.enumProp = 'enumerable'; + + Object.defineProperty(obj, 'nonEnumProp', { + value: 'non-enumerable', + enumerable: false + }); + + const forInProps = []; + for (const prop in obj) forInProps.push(prop); + return [obj, forInProps]; +} + +export function objectAllPropTest0500(){ + const obj = {}; + + const forInProps = []; + for (const prop in obj) forInProps.push(prop); + return [obj, forInProps]; +} + +export function objectAllPropTest0600(){ + const obj = { test: 'value' }; + + const forInProps = []; + for (const prop in obj) forInProps.push(prop); + return [obj, forInProps]; +} + +export function objectAllPropTest0800(){ + const sym1 = Symbol('sym1'); + const sym2 = Symbol('sym2'); + const obj = { [sym1]: 'value1' }; + Object.defineProperty(obj, sym2, { + value: 'value2', + enumerable: false + }); + + const forInProps = []; + for (const prop in obj) forInProps.push(prop); + return [obj, forInProps]; +} + +export function objectAllPropTest0900(){ + const obj = { + method1() {}, + method2: () => {} + }; + return obj; +} + +export function objectAllPropTest1000(){ + const obj = { a: 1 }; + + const forInProps = []; + for (const prop in obj) forInProps.push(prop); + return forInProps; +} +export function objectAllPropTest1001(){ + const obj = { a: 1 }; + const keys = Object.keys(obj); + return keys; +} +export function objectAllPropTest1002(){ + const obj = { a: 1 }; + + const ownNames = Object.getOwnPropertyNames(obj); + return ownNames; +} +export function objectAllPropTest1100(){ + const proto = { b: 2 }; + const obj = Object.create(proto); + obj.a = 1; + + const forInProps = []; + for (const prop in obj) forInProps.push(prop); + + return [obj, forInProps]; +} +export function objectAllPropTest1200(){ + const grandparent = { c: 3 }; + const parent = Object.create(grandparent); + parent.b = 2; + const child = Object.create(parent); + child.a = 1; + + const forInProps = []; + for (const prop in child) forInProps.push(prop); + return forInProps; +} +export function objectAllPropTest1300(){ + const proto = {}; + Object.defineProperty(proto, 'nonEnum', { + value: 'value', + enumerable: false + }); + proto.enumProp = 'enumerable'; + const obj = Object.create(proto); + + const forInProps = []; + for (const prop in obj) forInProps.push(prop); + return forInProps; +} +export function objectAllPropTest1400(){ + const proto = { prop: 'from proto' }; + const obj = Object.create(proto); + obj.prop = 'from obj'; + + const forInProps = []; + for (const prop in obj) forInProps.push(prop); + return [obj, forInProps]; +} +export function objectAllPropTest1500(){ + const instance = new SubClass(); + + const forInProps = []; + for (const prop in instance) forInProps.push(prop); + return forInProps; +} +export function objectAllPropTest1600(){ + class Test { + publicProp = 'public'; + privateProp = 'private'; + protectedProp = 'protected'; + } + + const instance = new Test(); + + const forInProps = []; + for (const prop in instance) forInProps.push(prop); + return forInProps; +} +export function objectAllPropTest1700(){ + const obj = {}; + + const forInProps = []; + for (const prop in obj) forInProps.push(prop); + return forInProps; +} +export function objectAllPropTest1800(){ + const proto = { b: 2 }; + const obj = Object.create(proto); + obj.a = 1; + + const ownProps = []; + for (const prop in obj) { + if (obj.hasOwnProperty(prop)) { + ownProps.push(prop); + } + } + return ownProps; +} +export function objectAllPropTest1900(){ + let current = null; + for (let i = 10; i >= 0; i--) { + current = Object.create(current); + current[`prop${i}`] = i; + } + + const forInProps = []; + for (const prop in current) forInProps.push(prop); + return forInProps; +} +export function objectAllPropTest2000(){ + const obj = { a: 1 }; + const proto1 = { b: 2 }; + const proto2 = { c: 3 }; + + Object.setPrototypeOf(obj, proto1); + const props1 = []; + for (const prop in obj) props1.push(prop); + + Object.setPrototypeOf(obj, proto2); + const props2 = []; + for (const prop in obj) props2.push(prop); + return [props1, props2]; +} +export function objectAllPropTest2100(arr){ + arr.customProp = 'custom'; + + const forInProps = []; + for (const prop in arr) forInProps.push(prop); + return [arr, forInProps]; +} +export function objectAllPropTest2200(){ + function testFunc() {} + testFunc.customProp = 'custom'; + + const forInProps = []; + for (const prop in testFunc) forInProps.push(prop); + return [testFunc, forInProps, Object.getOwnPropertyNames(testFunc)]; +} +export function objectAllPropTest2300(date){ + const forInProps = []; + for (const prop in date) forInProps.push(prop); + return [date, forInProps, Object.getOwnPropertyNames(date)]; +} +export function objectAllPropTest2400(regex){ + const forInProps = []; + for (const prop in regex) forInProps.push(prop); + return [regex, forInProps, Object.getOwnPropertyNames(regex)]; +} +export function objectAllPropTest2500(map){ + map.set('key', 'value'); + map.customProp = 'custom'; + + const forInProps = []; + for (const prop in map) forInProps.push(prop); + return [map, forInProps, Object.getOwnPropertyNames(map)]; +} +export function objectAllPropTest2600(set){ + set.add('value'); + set.customProp = 'custom'; + + const forInProps = []; + for (const prop in set) forInProps.push(prop); + return [set, forInProps, Object.getOwnPropertyNames(set)]; +} +export function objectAllPropTest2700(error){ + error.customProp = 'custom'; + + const forInProps = []; + for (const prop in error) forInProps.push(prop); + return [error, forInProps, Object.getOwnPropertyNames(error)]; +} +export function objectAllPropTest2800(num){ + num.customProp = 'custom'; + + const forInProps = []; + for (const prop in num) forInProps.push(prop); + return [num, forInProps, Object.getOwnPropertyNames(num)]; +} +export function objectAllPropTest2900(){ + const obj = { a: 1, b: 2 }; + Object.freeze(obj); + return obj; +} +export function objectAllPropTest3000(){ + const obj = { a: 1, b: 2 }; + Object.seal(obj); + return obj; +} +export function objectAllPropTest3600(obj){ + obj.self = obj; +} +export function objectAllPropTest3700(obj){ + for (let i = 0; i < 100; i++) { + obj[`prop${i}`] = i; + } + return Object.getOwnPropertyNames(obj); +} +export function objectAllPropTest3800(obj){ + obj.b = 2; +} +export function objectAllPropTest3801(obj){ + Object.defineProperty(obj, 'c', { + value: 3, + enumerable: false + }); + return Object.getOwnPropertyNames(obj); +} +export function objectAllPropTest3900(arr){ + arr[0] = 'a'; + arr[2] = 'c'; + + const forInProps = []; + for (const prop in arr) forInProps.push(prop); + return forInProps; +} +export function objectAllPropTest4000(){ + const obj = { a: 1 }; + const proto = { b: 2 }; + Object.setPrototypeOf(obj, proto); + + const allProps = listAllProperties(obj); + return allProps; +} +export function objectAllPropTest4200(grandparent){ + const parent = Object.create(grandparent); + parent.p = 'parent'; + Object.defineProperty(parent, 'pNonEnum', { + value: 'parent non-enum', + enumerable: false + }); + + const obj = Object.create(parent); + obj.o = 'own'; + Object.defineProperty(obj, 'oNonEnum', { + value: 'own non-enum', + enumerable: false + }); + + const forInProps = []; + for (const prop in obj) forInProps.push(prop); + return [obj, forInProps] +} \ No newline at end of file diff --git a/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectAllProp.test.ets b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectAllProp.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..bf4cbd483c6403c79154b1838f3f56b02e3d09bf --- /dev/null +++ b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectAllProp.test.ets @@ -0,0 +1,842 @@ +/* +* Copyright (C) 2024 HiHope Open Source Organization. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, TestType, Level, Size } from '@ohos/hypium'; +import { objectAllPropTest0100, objectAllPropTest0300, objectAllPropTest0400, + objectAllPropTest0500, + objectAllPropTest0600, + objectAllPropTest0800, + objectAllPropTest0900, + objectAllPropTest1000, + objectAllPropTest1001, + objectAllPropTest1002, + objectAllPropTest1100, + objectAllPropTest1200, + objectAllPropTest1300, + objectAllPropTest1400, + objectAllPropTest1500, + objectAllPropTest1700, + objectAllPropTest1800, + objectAllPropTest1900, + objectAllPropTest2000, + objectAllPropTest2100, + objectAllPropTest2200, + objectAllPropTest2300, + objectAllPropTest2400, + objectAllPropTest2500, + objectAllPropTest2600, + objectAllPropTest2700, + objectAllPropTest2800, + objectAllPropTest2900, + objectAllPropTest3000, + objectAllPropTest3600, + objectAllPropTest3700, + objectAllPropTest3800, + objectAllPropTest3801, + objectAllPropTest3900, + objectAllPropTest4000, + objectAllPropTest4200, + objectSetProto } from './ObjectAllProp'; + +function sleep(time: number): Promise { + return new Promise((re, je) => { + setTimeout(() => { + re(); + }, time); + }); +} + +export default function objectAllPropTest() { + describe('objectAllPropTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }) + beforeEach(async () => { + await sleep(100); + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }) + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }) + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }) + /** + * @tc.number SUB_OBJECT_ALL_PROP_0100 + * @tc.name objectAllPropTest0100 + * @tc.desc For... in Loop Basic Enumeration Test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest0100', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const enumerated = objectAllPropTest0100(); + expect(enumerated).assertDeepEquals(['a', 'b']); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_0200 + * @tc.name objectAllPropTest0200 + * @tc.desc Object. keys() basic testing + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest0200', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const obj = objectSetProto(); + expect(Object.keys(obj)).assertDeepEquals(['a']); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_0300 + * @tc.name objectAllPropTest0300 + * @tc.desc Object. getOwnPropertyNames() basic testing + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest0300', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const obj = objectAllPropTest0300(); + expect(Object.getOwnPropertyNames(obj)).assertDeepEquals(['a', 'b']); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_0400 + * @tc.name objectAllPropTest0400 + * @tc.desc Distinguish between enumerable and non enumerable attributes in testing + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest0400', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const result = objectAllPropTest0400(); + + expect(result[1]).assertDeepEquals(['enumProp']); + expect(Object.keys(result[0])).assertDeepEquals(['enumProp']); + expect(Object.getOwnPropertyNames(result[0])).assertDeepEquals(['enumProp', 'nonEnumProp']); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_0500 + * @tc.name objectAllPropTest0500 + * @tc.desc Empty object enumeration test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest0500', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const result = objectAllPropTest0500(); + + expect(result[1]).assertDeepEquals([]); + expect(Object.keys(result[0])).assertDeepEquals([]); + expect(Object.getOwnPropertyNames(result[0])).assertDeepEquals([]); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_0600 + * @tc.name objectAllPropTest0600 + * @tc.desc Single attribute object enumeration test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest0600', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const result = objectAllPropTest0600(); + + expect(result[1]).assertDeepEquals(['test']); + expect(Object.keys(result[0])).assertDeepEquals(['test']); + expect(Object.getOwnPropertyNames(result[0])).assertDeepEquals(['test']); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_0700 + * @tc.name objectAllPropTest0700 + * @tc.desc Multi attribute object enumeration test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest0700', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + interface BaseI{ + a: number; + b: number; + c: number; + } + const obj = { a: 1, b: 2, c: 3 } as BaseI; + + expect(Object.keys(obj)).assertDeepEquals(['a', 'b', 'c']); + expect(Object.keys(obj).length).assertEqual(3); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_0800 + * @tc.name objectAllPropTest0800 + * @tc.desc Symbol property enumeration test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest0800', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const result = objectAllPropTest0800(); + + expect(result[1].toString()).assertEqual([].toString()); + expect(Object.keys(result[0]).toString()).assertEqual([].toString()); + expect(Object.getOwnPropertyNames(result[0]).toString()).assertEqual([].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_0900 + * @tc.name objectAllPropTest0900 + * @tc.desc Method attribute enumeration test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest0900', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const obj = objectAllPropTest0900(); + expect(Object.keys(obj).toString()).assertEqual(['method1', 'method2'].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_1000 + * @tc.name objectAllPropTest1000 + * @tc.desc Three methods for testing return value types + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest1000', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const forInProps = objectAllPropTest1000(); + expect(Array.isArray(forInProps)).assertEqual(true); + expect(typeof forInProps[0]).assertEqual('string'); + + const keys = objectAllPropTest1001(); + expect(Array.isArray(keys)).assertEqual(true); + expect(typeof keys[0]).assertEqual('string'); + + const ownNames = objectAllPropTest1002(); + expect(Array.isArray(keys)).assertEqual(true); + expect(typeof ownNames[0]).assertEqual('string'); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_1100 + * @tc.name objectAllPropTest1100 + * @tc.desc Single level prototype chain enumeration testing + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest1100', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const result = objectAllPropTest1100() as (string[] | object)[]; + expect(result[1].toString()).assertEqual(['a', 'b'].toString()); + + expect(Object.keys(result[0]).toString()).assertEqual(['a'].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_1200 + * @tc.name objectAllPropTest1200 + * @tc.desc Multi level prototype chain enumeration testing + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest1200', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const forInProps = objectAllPropTest1200(); + expect(forInProps.toString()).assertEqual(['a', 'b', 'c'].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_1300 + * @tc.name objectAllPropTest1300 + * @tc.desc Non enumerable attribute testing in prototype chain + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest1300', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const forInProps = objectAllPropTest1300(); + expect(forInProps.toString()).assertEqual(['enumProp'].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_1400 + * @tc.name objectAllPropTest1400 + * @tc.desc Attribute Coverage Prototype Chain Attribute Testing + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest1400', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + interface BaseI{ + prop?: string; + } + const result = objectAllPropTest1400() as (string[] | BaseI)[]; + expect(result[1].toString()).assertEqual(['prop'].toString()); + expect((result[0] as BaseI).prop).assertEqual('from obj'); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_1500 + * @tc.name objectAllPropTest1500 + * @tc.desc Class Inheritance Enumeration Test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest1500', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const forInProps = objectAllPropTest1500(); + expect(forInProps).assertContain('subClassProp'); + expect(forInProps).assertContain('baseClassProp'); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_1600 + * @tc.name objectAllPropTest1600 + * @tc.desc Class private property enumeration test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest1600', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + class Test { + public publicProp = 'public'; + private privateProp = 'private'; + protected protectedProp = 'protected'; + } + + const instance = new Test(); + expect(Object.keys(instance)).assertContain('publicProp'); + expect(Object.keys(instance)).assertContain('privateProp'); + expect(Object.keys(instance)).assertContain('protectedProp'); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_1700 + * @tc.name objectAllPropTest1700 + * @tc.desc Object. prototype property enumeration test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest1700', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const forInProps = objectAllPropTest1700(); + expect(forInProps.toString()).assertEqual([].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_1800 + * @tc.name objectAllPropTest1800 + * @tc.desc HasOwnProperty filtering test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest1800', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const forInProps = objectAllPropTest1800(); + expect(forInProps.toString()).assertEqual(['a'].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_1900 + * @tc.name objectAllPropTest1900 + * @tc.desc The influence of prototype chain length on enumeration + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest1900', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const forInProps = objectAllPropTest1900(); + expect(forInProps.length).assertEqual(11); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_2000 + * @tc.name objectAllPropTest2000 + * @tc.desc Enumeration testing after modifying the prototype + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest2000', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const result = objectAllPropTest2000(); + expect(result[0].toString()).assertEqual(['a', 'b'].toString()); + expect(result[1].toString()).assertEqual(['a', 'c'].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_2100 + * @tc.name objectAllPropTest2100 + * @tc.desc Array object enumeration test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest2100', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const arr = [1, 2, 3]; + const result = objectAllPropTest2100(arr) as (string[] | number[])[]; + + expect(result[1].toString()).assertEqual(['0', '1', '2', 'customProp'].toString()); + expect(Object.keys(result[0]).toString()).assertEqual(['0', '1', '2', 'customProp'].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_2200 + * @tc.name objectAllPropTest2200 + * @tc.desc Function object enumeration test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest2200', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const result = objectAllPropTest2200(); + + expect(result[1]).assertContain('customProp'); + expect(result[1]).not().assertContain('name'); + expect(result[1]).not().assertContain('length'); + + expect(Object.keys(result[0]).toString()).assertEqual(['customProp'].toString()); + + expect(result[2].toString()).assertEqual(['length', 'name', 'prototype', 'customProp'].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_2300 + * @tc.name objectAllPropTest2300 + * @tc.desc Date Object Enumeration Test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest2300', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const date = new Date(); + const result = objectAllPropTest2300(date) as (string[] | Date)[]; + + expect(result[1].toString()).assertEqual([].toString()); + + expect(Object.keys(date).toString()).assertEqual([].toString()); + expect(result[2].toString()).assertEqual([].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_2400 + * @tc.name objectAllPropTest2400 + * @tc.desc RegExp Object Enumeration Test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest2400', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const regex = new RegExp(/test/gi); + const result = objectAllPropTest2400(regex) as (string[] | RegExp)[]; + + expect(result[1].toString()).assertEqual([].toString()); + + expect(Object.keys(regex).toString()).assertEqual([].toString()); + expect(result[2].toString()).assertEqual(['lastIndex'].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_2500 + * @tc.name objectAllPropTest2500 + * @tc.desc Map Object Enumeration Test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest2500', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const map = new Map(); + const result = objectAllPropTest2500(map) as (string[] | Map)[]; + + expect(result[1].toString()).assertEqual(['customProp'].toString()); + + expect(Object.keys(map).toString()).assertEqual(['customProp'].toString()); + expect(result[2].toString()).assertEqual(['customProp'].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_2600 + * @tc.name objectAllPropTest2600 + * @tc.desc Set Object Enumeration Test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest2600', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const set = new Set(); + const result = objectAllPropTest2600(set) as (string[] | Set)[]; + + expect(result[1].toString()).assertEqual(['customProp'].toString()); + + expect(Object.keys(set).toString()).assertEqual(['customProp'].toString()); + expect(result[2].toString()).assertEqual(['customProp'].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_2700 + * @tc.name objectAllPropTest2700 + * @tc.desc Error Object Enumeration Test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest2700', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const error = new Error('Test error'); + const result = objectAllPropTest2700(error) as (string[] | Error)[]; + expect(result[1].toString()).assertEqual(['customProp'].toString()); + + expect(Object.keys(error).toString()).assertEqual(['customProp'].toString()); + expect(result[2].toString()).assertEqual(['message','errorfunc', 'stack', 'topstack', 'customProp'].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_2800 + * @tc.name objectAllPropTest2800 + * @tc.desc Number Object Enumeration Test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest2800', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const numObj = new Number(123); + const result = objectAllPropTest2800(numObj) as (string[] | Number)[]; + expect(result[1].toString()).assertEqual(['customProp'].toString()); + + expect(Object.keys(numObj).toString()).assertEqual(['customProp'].toString()); + expect(result[2].toString()).assertEqual(['customProp'].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_2900 + * @tc.name objectAllPropTest2900 + * @tc.desc Freeze Object Enumeration Test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest2900', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const obj = objectAllPropTest2900(); + expect(Object.keys(obj).toString()).assertEqual(['a', 'b'].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_3000 + * @tc.name objectAllPropTest3000 + * @tc.desc seal Object Enumeration Test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest3000', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const obj = objectAllPropTest3000(); + expect(Object.keys(obj).toString()).assertEqual(['a', 'b'].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_3100 + * @tc.name objectAllPropTest3100 + * @tc.desc First level nested object enumeration test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest3100', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + interface BaseI{ + b: number; + c: number; + } + interface BaseI1{ + a: number; + nested: BaseI; + } + const obj: BaseI1 = { + a: 1, + nested: { + b: 2, + c: 3 + } + }; + expect(Object.keys(obj).toString()).assertEqual(['a', 'nested'].toString()); + expect(Object.keys(obj).length).assertEqual(2); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_3200 + * @tc.name objectAllPropTest3200 + * @tc.desc Multi level nested object enumeration test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest3200', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + interface BaseI{ + value: string; + } + interface BaseI1{ + level3: BaseI; + } + interface BaseI2{ + level2: BaseI1; + } + interface BaseI3{ + level1: BaseI2; + } + const obj: BaseI3 = { + level1: { + level2: { + level3: { + value: 'deep' + } + } + } + }; + + expect(Object.keys(obj).toString()).assertEqual(['level1'].toString()); + expect(Object.keys(obj.level1).toString()).assertEqual(['level2'].toString()); + expect(Object.keys(obj.level1.level2).toString()).assertEqual(['level3'].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_3300 + * @tc.name objectAllPropTest3300 + * @tc.desc Nested object enumeration test containing arrays + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest3300', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + interface BaseI{ + tags: string[]; + } + interface BaseI1{ + name: string; + items: number[]; + details: BaseI; + } + const obj: BaseI1 = { + name: 'test', + items: [1, 2, 3], + details: { + tags: ['a', 'b'] + } + }; + + expect(Object.keys(obj).toString()).assertEqual(['name', 'items', 'details'].toString()); + expect(Object.keys(obj.items).toString()).assertEqual(['0', '1', '2'].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_3400 + * @tc.name objectAllPropTest3400 + * @tc.desc Nested object enumeration test containing functions + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest3400', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + class Methods{ + func1(){} + func2: ()=>void = ()=>{} + } + class BaseC{ + prop: string = 'value'; + methods: Methods = new Methods(); + } + const obj = new BaseC(); + + expect(Object.keys(obj).toString()).assertEqual(['prop', 'methods'].toString()); + expect(Object.keys(obj.methods).toString()).assertEqual(['func2'].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_3500 + * @tc.name objectAllPropTest3500 + * @tc.desc Mixed type nested object enumeration test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest3500', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + interface BaseI{ + e: number; + } + interface BaseI1{ + a: number; + b: string; + c: boolean; + d: BaseI; + f: number[]; + g: ()=>void; + h: Date; + } + const obj: BaseI1 = { + a: 123, + b: 'string', + c: true, + d: { e: 456 }, + f: [7, 8, 9], + g: () => {}, + h: new Date() + }; + + expect(Object.keys(obj).toString()).assertEqual(['a', 'b', 'c', 'd', 'f', 'g', 'h'].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_3600 + * @tc.name objectAllPropTest3600 + * @tc.desc Loop reference object enumeration test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest3600', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + interface BaseI{ + a: number; + } + const obj: BaseI = { a: 1 }; + objectAllPropTest3600(obj); + expect(Object.keys(obj).toString()).assertEqual(['a', 'self'].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_3700 + * @tc.name objectAllPropTest3700 + * @tc.desc Large object enumeration testing + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest3700', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + interface BaseI{ + } + const obj: BaseI = { }; + const ownProto = objectAllPropTest3700(obj); + expect(Object.keys(obj).length).assertEqual(100); + expect(ownProto.length).assertEqual(100); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_3800 + * @tc.name objectAllPropTest3800 + * @tc.desc Object enumeration test for dynamically adding attributes + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest3800', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + interface BaseI{ + a: number; + } + const obj: BaseI = { a: 1 }; + objectAllPropTest3800(obj); + expect(Object.keys(obj).toString()).assertEqual(['a', 'b'].toString()); + const ownProto = objectAllPropTest3801(obj); + expect(Object.keys(obj).toString()).assertEqual(['a', 'b'].toString()); + expect(ownProto.toString()).assertEqual(['a', 'b', 'c'].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_3900 + * @tc.name objectAllPropTest3900 + * @tc.desc Sparse array enumeration test + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest3900', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const arr = []; + const forInProps = objectAllPropTest3900(arr); + + expect(forInProps.toString()).assertEqual(['0', '2'].toString()); + expect(Object.keys(arr).toString()).assertEqual(['0', '2'].toString()); + expect(Object.getOwnPropertyNames(arr).toString()).assertEqual(['0', '2', 'length'].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_4000 + * @tc.name objectAllPropTest4000 + * @tc.desc Basic testing of listAllProperties function + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest4000', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + const allProps = objectAllPropTest4000(); + + expect(allProps).assertContain('a'); + expect(allProps).assertContain('b'); + expect(allProps).assertContain('constructor'); + expect(allProps).assertContain('toString'); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_4100 + * @tc.name objectAllPropTest4100 + * @tc.desc Test the order of return values of enumeration methods + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest4100', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + interface BaseI{ + '3': string; + '1': string; + '2': string; + 'a': string; + 'b': string; + } + const obj: BaseI = { + '3': 'three', + '1': 'one', + '2': 'two', + 'a': 'A', + 'b': 'B' + }; + + expect(Object.keys(obj).toString()).assertEqual(['1', '2', '3', 'a', 'b'].toString()); + }); + + /** + * @tc.number SUB_OBJECT_ALL_PROP_4200 + * @tc.name objectAllPropTest4200 + * @tc.desc Comparative testing of comprehensive enumeration methods + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectAllPropTest4200', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + interface BaseI{ + g: string; + } + const grandparent: BaseI = { g: 'grandparent' }; + + const result = objectAllPropTest4200(grandparent) as (BaseI | string[])[]; + + expect(result[1].toString()).assertEqual(['o', 'p', 'g'].toString()); + expect(Object.keys(result[0]).toString()).assertEqual(['o'].toString()); + expect(Object.getOwnPropertyNames(result[0]).toString()).assertEqual(['o', 'oNonEnum'].toString()); + }); + + }) +} \ No newline at end of file diff --git a/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectAndProp.js b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectAndProp.js new file mode 100644 index 0000000000000000000000000000000000000000..f1102e448fd1e665ac64b003b3ed9a3c6d5795b7 --- /dev/null +++ b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectAndProp.js @@ -0,0 +1,108 @@ + +export function createObj(){ + const proto = { }; + const obj = Object.create(proto, { + nonConfigurable: { + value: 'cannotDelete', + configurable: false, // 不可删除 + enumerable: true + }, + base: { + value: 'baseVal', + configurable: true, // 可删除 + enumerable: true + } + }); + return obj; +} +export function deleteNonConfigurable(obj){ + try { + let boo = delete obj.nonConfigurable; + return boo; + } catch (e){ + return false + } +} +export function deleteBase(obj){ + let boo = delete obj.base; + return boo; +} + +export function symbolTest(){ + const sym1 = Symbol("key1"); + const sym2 = Symbol("key2"); + const myObj = { }; + myObj[sym1] = "sym1-val"; + myObj[sym2] = "sym2-val"; + return [sym1, sym2, myObj] +} + +export function symbolTest1(){ + const sym1 = Symbol.for('key1'); + const sym2 = Symbol.for('key1'); + const myObj = {} + myObj[sym1] = "global-val"; + return [sym1, sym2, myObj] +} + +export function objectPropTest3200(){ + const obj = new Object(); + obj.prop = "value"; + return obj; +} +export function objectPropTest3200Del(obj){ + delete obj.prop; +} +export function objectPropTest3200_1(obj){ + return obj.hasOwnProperty("prop") +} +export function objectPropTest3300(){ + Object.prototype.protoProp = "proto-val"; + const obj = new Object(); + return delete obj.protoProp; +} +export function objectPropTest3300_1(){ + Object.prototype.protoProp = "proto-val"; + const obj = new Object(); + delete obj.protoProp; + return Object.prototype.protoProp; +} +export function objectPropTest3300_2(){ + Object.prototype.protoProp = "proto-val"; + const obj = new Object(); + delete Object.prototype.protoProp; + return Object.prototype.protoProp; +} +export function objectPropTest4600(){ + const parent = { "inherited": "val" }; + const child = Object.create(parent); + child.own = "own-val"; + let propCount = 0; + for (const prop in child) { + propCount++; + } + return propCount; +} +export function objectPropTest4700(){ + const parent = { inherited: "val" }; + const child = Object.create(parent); + child.own = "own-val"; + return [child.hasOwnProperty("own"), child.hasOwnProperty("inherited")]; +} +export function objectPropTest5500(){ + const baseSpec = { weight: '1kg', material: 'plastic' }; + const toolProto = Object.create(baseSpec); + toolProto.use = () => 'cut materials'; + + const toolBox = { + name: 'Hand Tool Box', + tools: [ + Object.create(toolProto), + Object.create(toolProto) + ] + }; + return toolBox; +} +export function objectPropTest6600(grandparent){ + return Object.create(grandparent); +} \ No newline at end of file diff --git a/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectAndProp.test.ets b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectAndProp.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..5c4d24455aef01bf9530a214b5b14f4812ae54bf --- /dev/null +++ b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectAndProp.test.ets @@ -0,0 +1,1601 @@ +/* +* Copyright (C) 2024 HiHope Open Source Organization. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, TestType, Level, Size } from '@ohos/hypium'; +import { deleteBase, deleteNonConfigurable, createObj, symbolTest, symbolTest1, + objectPropTest3200, + objectPropTest3200Del, + objectPropTest3200_1, + objectPropTest3300, + objectPropTest3300_1, + objectPropTest3300_2, + objectPropTest4600, + objectPropTest4700, + objectPropTest5500, + objectPropTest6600} from './ObjectAndProp'; + +interface Electronic { + brand: string; + price: number; + specs?: Record; + objArr: Object[]; +} + +interface GeneratedTypeLiteralInterface_1 { + name: string; + email: string; +} + +interface User { + id: number; + info: GeneratedTypeLiteralInterface_1; +} + +interface Tool { + type: string; + use: () => string; +} + +interface GeneratedTypeLiteralInterface_2 { + start: string; + end: string; +} + +interface GeneratedObjectLiteralInterface_1 { + orderId: string; + product: string; + validPeriod: GeneratedTypeLiteralInterface_2; +} + +function sleep(time: number): Promise { + return new Promise((re, je) => { + setTimeout(() => { + re(); + }, time); + }); +} + +export default function objectAndPropTest() { + describe('objectAndPropTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }) + beforeEach(async () => { + await sleep(100); + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }) + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }) + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }) + /** + * @tc.number SUB_OBJECT_PROP_0100 + * @tc.name objectPropTest0100 + * @tc.desc test Object creation via new Object() + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest0100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const obj = new Object(); + expect(typeof obj).assertEqual('object'); + expect(obj.constructor).assertEqual(Object); + }) + + /** + * @tc.number SUB_OBJECT_PROP_0200 + * @tc.name objectPropTest0200 + * @tc.desc test dot notation to set string property + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest0200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + make: string; + } + const myCar: UserData = { "make": "Ford"} + expect(myCar.make).assertEqual("Ford"); + expect(typeof myCar.make).assertEqual("string"); + }) + + /** + * @tc.number SUB_OBJECT_PROP_0300 + * @tc.name objectPropTest0300 + * @tc.desc test dot notation to set number property + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest0300', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + year: number; + } + + const myCar: UserData = { "year": 1969} + expect(myCar.year).assertEqual(1969); + expect(typeof myCar.year).assertEqual("number"); + }) + + /** + * @tc.number SUB_OBJECT_PROP_0400 + * @tc.name objectPropTest0400 + * @tc.desc test undefined value of unassigned property + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest0400', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + make: string; + noProperty?: object; + } + + const myCar: UserData = { "make": "Ford"} + expect(myCar.noProperty).assertEqual(undefined); + expect(myCar.noProperty).not().assertEqual(null); + }) + + /** + * @tc.number SUB_OBJECT_PROP_0500 + * @tc.name objectPropTest0500 + * @tc.desc test case sensitivity of property names + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest0500', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + model: string; + MODEL: string; + } + + const myCar: UserData = { "model": "Mustang", "MODEL": "F-150"}; + expect(myCar.model).assertEqual("Mustang"); + expect(myCar.MODEL).assertEqual("F-150"); + }) + + /** + * @tc.number SUB_OBJECT_PROP_0600 + * @tc.name objectPropTest0600 + * @tc.desc test bracket notation to set string property + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest0600', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + obj: Record; + } + const myCar: UserData = { obj : {['make']:"Ford"}} + expect(myCar.obj["make"]).assertEqual("Ford"); + }) + + /** + * @tc.number SUB_OBJECT_PROP_0700 + * @tc.name objectPropTest0700 + * @tc.desc test bracket notation to set number property + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest0700', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + obj: Record; + } + const myCar: UserData = { obj : {['year'] : 1969}}; + expect(myCar.obj["year"]).assertEqual(1969); + }) + + /** + * @tc.number SUB_OBJECT_PROP_0800 + * @tc.name objectPropTest0800 + * @tc.desc test property name with space (bracket only) + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest0800', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + obj: Record; + } + const myObj: UserData = { obj : {['date created']: "2024-01-01"}} + expect(myObj.obj["date created"]).assertEqual("2024-01-01"); + expect(myObj.obj["dateCreated"]).assertEqual(undefined); + }) + + /** + * @tc.number SUB_OBJECT_PROP_0900 + * @tc.name objectPropTest0900 + * @tc.desc test property name with hyphen (bracket only) + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest0900', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + obj: Record; + } + const myObj: UserData = { obj : { "user-name": "john_doe" }}; + expect(myObj.obj["user-name"]).assertEqual("john_doe"); + expect(myObj.obj["userName"]).assertEqual(undefined); + }) + + /** + * @tc.number SUB_OBJECT_PROP_1000 + * @tc.name objectPropTest1000 + * @tc.desc test property name starting with number (bracket only) + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest1000', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + obj: Record; + } + const myObj: UserData = { obj : {"123-id": 123} }; + expect(myObj.obj["123-id"]).assertEqual(123); + }) + + /** + * @tc.number SUB_OBJECT_PROP_1100 + * @tc.name objectPropTest1100 + * @tc.desc test empty string as property name + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest1100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + obj: Record; + } + const myObj: UserData = { obj : { "": "empty-value"} } + expect(myObj.obj[""]).assertEqual("empty-value"); + }) + + /** + * @tc.number SUB_OBJECT_PROP_1200 + * @tc.name objectPropTest1200 + * @tc.desc test variable as property name (bracket notation) + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest1200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + obj: Record; + } + const myCar: UserData = { obj : {} }; + const propName = "make"; + myCar.obj[propName] = "Ford"; + expect(myCar.obj[propName]).assertEqual("Ford"); + }) + + /** + * @tc.number SUB_OBJECT_PROP_1300 + * @tc.name objectPropTest1300 + * @tc.desc test random number as property name + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest1300', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + obj: Record; + } + const myObj: UserData = { obj : {} }; + const rand = Math.random(); + myObj.obj[rand] = "random-value"; + const randStr = rand.toString(); + expect(myObj.obj[rand]).assertEqual("random-value"); + expect(myObj.obj[randStr]).assertEqual("random-value"); + }) + + /** + * @tc.number SUB_OBJECT_PROP_1400 + * @tc.name objectPropTest1400 + * @tc.desc test object as property name (toString conversion) + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest1400', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface UserData { + obj: Record; + } + const myObj: UserData = { obj : {} }; + const keyObj = new Object(); + myObj.obj[String(keyObj)] = "object-key-value"; + const keyStr = keyObj.toString(); + expect(myObj.obj[keyStr]).assertEqual("object-key-value"); + expect(myObj.obj[String(keyObj)]).assertEqual("object-key-value"); + }) + + /** + * @tc.number SUB_OBJECT_PROP_1500 + * @tc.name objectPropTest1500 + * @tc.desc test dynamic property name assignment via variable + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest1500', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface UserData { + obj: Record; + } + const myCar: UserData = { obj : {} }; + let propertyName = "make"; + myCar.obj[propertyName] = "Ford"; + propertyName = "model"; + myCar.obj[propertyName] = "Mustang"; + expect(myCar.obj["make"]).assertEqual("Ford"); + expect(myCar.obj["model"]).assertEqual("Mustang"); + }) + + /** + * @tc.number SUB_OBJECT_PROP_1600 + * @tc.name objectPropTest1600 + * @tc.desc test for...in loop to enumerate properties + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest1600', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface UserData { + obj: Record; + } + const myCar: UserData = { obj : {} }; + myCar.obj["make"] = "Ford"; + myCar.obj["model"] = "Mustang"; + myCar.obj["year"] = 1969; + const props: (string | number)[] = []; + Object.entries(myCar.obj).forEach((one: (string | number)[]) => { + props.push(one[0]); + }) + expect(props).assertDeepEquals(["make", "model", "year"]); + }) + + /** + * @tc.number SUB_OBJECT_PROP_1700 + * @tc.name objectPropTest1700 + * @tc.desc test hasOwnProperty to filter own properties + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest1700', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface UserData{ + obj : Record; + } + const myCar : UserData = { obj : {} }; + myCar.obj["make"] = "Ford"; + myCar.obj.extra = "proto-prop"; + const ownProps: string[] = []; + Object.entries(myCar.obj).forEach((one: string[]) => { + ownProps.push(one[0]); + }) + expect(ownProps).assertContain("make"); + }) + + /** + * @tc.number SUB_OBJECT_PROP_1800 + * @tc.name objectPropTest1800 + * @tc.desc test showProps function output format + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest1800', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface UserData { + obj: Record; + } + const myCar: UserData = { obj : {} }; + myCar.obj["make"] = "Ford"; + myCar.obj["model"] = "Mustang"; + myCar.obj["year"] = 1969; + let showProps: (obj: object, objName: string) => string = (obj: object, objName: string): string => { + let result = ""; + Object.entries(myCar.obj).forEach((one: (string|number)[]) => { + result += `${objName}.${one[0]} = ${one[1]}\n`; + }) + return result; + } + const expected = "myCar.make = Ford\nmyCar.model = Mustang\nmyCar.year = 1969\n"; + const result = showProps(myCar.obj, "myCar"); + expect(result).assertEqual(expected); + }) + + /** + * @tc.number SUB_OBJECT_PROP_1900 + * @tc.name objectPropTest1900 + * @tc.desc test number as property name (auto-convert to string) + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest1900', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + obj: Record; + } + const myObj: UserData = { obj : {} }; + myObj.obj[123] = "number-key"; + expect(myObj.obj[123]).assertEqual("number-key"); + expect(myObj.obj["123"]).assertEqual("number-key"); + }) + + /** + * @tc.number SUB_OBJECT_PROP_2000 + * @tc.name objectPropTest2000 + * @tc.desc test boolean as property name (auto-convert to string) + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest2000', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + obj: Record; + } + const myObj: UserData = { obj : {} }; + myObj.obj["true"] = "bool-key"; + expect(myObj.obj["true"]).assertEqual("bool-key"); + }) + + /** + * @tc.number SUB_OBJECT_PROP_2100 + * @tc.name objectPropTest2100 + * @tc.desc test reassign property via dot notation + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest2100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + make: string; + } + + const myCar: UserData = { "make": "Ford" } + myCar.make = "Ford"; + myCar.make = "Toyota"; + expect(myCar.make).assertEqual("Toyota"); + }) + + /** + * @tc.number SUB_OBJECT_PROP_2200 + * @tc.name objectPropTest2200 + * @tc.desc test reassign property via bracket notation + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest2200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + year: number; + } + + const myCar: UserData = { "year": 1969 } + myCar.year = 1969; + myCar.year = 2024; + expect(myCar.year).assertEqual(2024); + }) + + /** + * @tc.number SUB_OBJECT_PROP_2300 + * @tc.name objectPropTest2300 + * @tc.desc test Symbol as unique property name + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest2300', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + const myObj = symbolTest(); + let sym1 = myObj[0]; + let sym2 = myObj[1]; + expect(myObj[2][sym1]).assertEqual("sym1-val"); + expect(myObj[2][sym2]).assertEqual("sym2-val"); + expect(sym1).not().assertDeepEquals(sym2); + }) + + /** + * @tc.number SUB_OBJECT_PROP_2400 + * @tc.name objectPropTest2400 + * @tc.desc test global Symbol (Symbol.for) as property name + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest2400', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + const myObj = symbolTest1(); + let sym1 = myObj[0]; + let sym2 = myObj[1]; + expect(myObj[2][sym2]).assertEqual("global-val"); + expect(sym1).assertDeepEquals(sym2); + }) + + /** + * @tc.number SUB_OBJECT_PROP_2500 + * @tc.name objectPropTest2500 + * @tc.desc test property name with special char ($, _) + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest2500', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + $price: number; + user_name: string; + } + + const obj: UserData = { "$price": 19.99, "user_name": "jane" } + expect(obj.$price).assertEqual(19.99); + expect(obj.user_name).assertEqual("jane"); + }) + + /** + * @tc.number SUB_OBJECT_PROP_2600 + * @tc.name objectPropTest2600 + * @tc.desc test empty Object property enumeration + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest2600', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + obj: Record; + } + const emptyObj: UserData = { obj: { } }; + const props: string[] = []; + Object.entries(emptyObj.obj).forEach((one: string[]) => { + props.push(one[1]); + }) + expect(props.length).assertEqual(0); + }) + + /** + * @tc.number SUB_OBJECT_PROP_2700 + * @tc.name objectPropTest2700 + * @tc.desc test boolean type property + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest2700', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + isActive: boolean; + } + + const config: UserData = { "isActive": true } + expect(config.isActive).assertTrue(); + expect(typeof config.isActive).assertEqual("boolean"); + }) + + /** + * @tc.number SUB_OBJECT_PROP_2800 + * @tc.name objectPropTest2800 + * @tc.desc test null vs undefined property value + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest2800', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + undefProp?: object; + nullProp?: object | null; + } + + const data: UserData = { "nullProp": null } + expect(data.nullProp).assertEqual(null); + expect(data.undefProp).assertEqual(undefined); + expect(data.nullProp).not().assertEqual(data.undefProp); + }) + + /** + * @tc.number SUB_OBJECT_PROP_2900 + * @tc.name objectPropTest2900 + * @tc.desc test nested Object as property value + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest2900', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface UserData { + info: Record; + } + const user: UserData = { info: { ['name'] : "Alice"} }; + expect(user.info["name"]).assertEqual("Alice"); + }) + + /** + * @tc.number SUB_OBJECT_PROP_3000 + * @tc.name objectPropTest3000 + * @tc.desc test Array as property value + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest3000', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface UserData { + obj: Record; + } + const cart: UserData = { obj: {} }; + cart.obj["items"] = ["apple", "banana"]; + expect(cart.obj["items"].length).assertEqual(2); + expect(cart.obj["items"][0]).assertEqual("apple"); + cart.obj["items"].push("orange"); + expect(cart.obj["items"].length).assertEqual(3); + }) + + /** + * @tc.number SUB_OBJECT_PROP_3100 + * @tc.name objectPropTest3100 + * @tc.desc test function as Object property (method) + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest3100', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface UserData { + obj: Record; + } + const calc: UserData = { obj: {} }; + calc.obj["add"] = (a: number, b: number) => a + b; + expect(calc.obj["add"](2, 3)).assertEqual(5); + expect(typeof calc.obj["add"]).assertEqual("function"); + }) + + /** + * @tc.number SUB_OBJECT_PROP_3200 + * @tc.name objectPropTest3200 + * @tc.desc test delete operator for own property + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest3200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface BaseI{ + prop?: string; + } + const obj: BaseI = objectPropTest3200() as BaseI; + expect(obj.prop).assertEqual("value"); + objectPropTest3200Del(obj); + expect(obj.prop).assertEqual(undefined); + expect(objectPropTest3200_1(obj)).assertFalse(); + }) + + /** + * @tc.number SUB_OBJECT_PROP_3300 + * @tc.name objectPropTest3300 + * @tc.desc test delete operator cannot delete prototype property + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest3300', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + expect(objectPropTest3300()).assertTrue(); + expect(objectPropTest3300_1()).assertEqual("proto-val"); + expect(objectPropTest3300_2()).assertUndefined(); + }) + + /** + * @tc.number SUB_OBJECT_PROP_3400 + * @tc.name objectPropTest3400 + * @tc.desc test NaN as property value + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest3400', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + invalid?: number; + } + + const math: UserData = { } + math.invalid = NaN; + expect(Number.isNaN(math.invalid)).assertTrue(); + expect(math.invalid).not().assertEqual(math.invalid); + + }) + + /** + * @tc.number SUB_OBJECT_PROP_3500 + * @tc.name objectPropTest3500 + * @tc.desc test Infinity as property value + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest3500', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + upper?: number; + lower?: number; + } + + const limit: UserData = { } + limit.upper = Infinity; + limit.lower = -Infinity; + expect(limit.upper).assertEqual(Infinity); + expect(limit.lower).assertEqual(-Infinity); + + }) + + /** + * @tc.number SUB_OBJECT_PROP_3600 + * @tc.name objectPropTest3600 + * @tc.desc test runtime-generated dynamic property name + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest3600', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface UserData { + obj: Record; + } + const userData: UserData = { obj: {} }; + const prefix = "item_"; + const id = "456"; + const dynamicKey = `${prefix}${id}`; + userData.obj[dynamicKey] = "dynamic-val"; + expect(userData.obj[dynamicKey]).assertEqual("dynamic-val"); + expect(userData.obj["item_456"]).assertEqual("dynamic-val"); + + }) + + /** + * @tc.number SUB_OBJECT_PROP_3700 + * @tc.name objectPropTest3700 + * @tc.desc test Object.keys() to get own properties + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest3700', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface UserData { + obj: Record; + } + const myCar: UserData = { obj: {} }; + myCar.obj.make = "Ford"; + myCar.obj.model = "Mustang"; + myCar.obj.extra = "proto-val"; + const keys = Object.keys(myCar.obj); + expect(keys).assertDeepEquals(["make", "model", "extra"]); + + }) + + /** + * @tc.number SUB_OBJECT_PROP_3800 + * @tc.name objectPropTest3800 + * @tc.desc test Date object as property value + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest3800', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + date?: Date; + } + const event: UserData = {} + event.date = new Date("2024-05-20"); + expect(event.date instanceof Date).assertTrue(); + expect(event.date.getFullYear()).assertEqual(2024); + + }) + + /** + * @tc.number SUB_OBJECT_PROP_3900 + * @tc.name objectPropTest3900 + * @tc.desc test frozen property value (Object.freeze) + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest3900', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface Frozen{ + val: string; + } + interface UserData { + obj: Record; + } + const myCar: UserData = { obj: {} }; + const frozen: Frozen = { val: "frozen" }; + myCar.obj.data = frozen; + myCar.obj.data.val = "modified"; + expect(myCar.obj.data.val).assertEqual("modified"); + + }) + + /** + * @tc.number SUB_OBJECT_PROP_4000 + * @tc.name objectPropTest4000 + * @tc.desc test comprehensive property operation (create/access/modify/delete) + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest4000', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL1, () => { + interface UserData { + name: string; + price: number | undefined; + } + const product: UserData = { "name" : "Laptop", "price" : 999 } + expect(product.name).assertEqual("Laptop"); + expect(product.price).assertEqual(999); + // Modify + product.price = 899; + expect(product.price).assertEqual(899); + // Delete + product.price = undefined; + expect(product.price).assertEqual(undefined); + + }) + + /** + * @tc.number SUB_OBJECT_PROP_4100 + * @tc.name objectPropTest4100 + * @tc.desc test property name with special chars (e.g. #, @) + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest4100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + obj: Record; + } + const myCar: UserData = { obj: {} }; + myCar.obj["#tag"] = "test"; + myCar.obj["@user"] = "alice"; + expect(myCar.obj["#tag"]).assertEqual("test"); + expect(myCar.obj["@user"]).assertEqual("alice"); + + }) + + /** + * @tc.number SUB_OBJECT_PROP_4200 + * @tc.name objectPropTest4200 + * @tc.desc test multi-level nested Object access + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest4200', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface Address { + city : string; + } + interface User { + address : Address; + } + interface UserData { + user: User; + } + const data: UserData = { "user" : { "address" : { "city" : "Beijing" }} } + expect(data.user.address.city).assertEqual("Beijing"); + + }) + + /** + * @tc.number SUB_OBJECT_PROP_4300 + * @tc.name objectPropTest4300 + * @tc.desc test Array of Objects as property value + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest4300', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface User { + name : string; + } + interface UserData { + users: User[]; + } + const list: UserData = { "users" : [{ "name": "Alice" }, { "name": "Bob" }] } + expect(list.users.length).assertEqual(2); + expect(list.users[0].name).assertEqual("Alice"); + + }) + + /** + * @tc.number SUB_OBJECT_PROP_4400 + * @tc.name objectPropTest4400 + * @tc.desc test property value as null (explicit assignment) + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest4400', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + nullVal: object | null; + } + const obj: UserData = { "nullVal" : null } + expect(obj.nullVal).assertEqual(null); + expect(obj.nullVal).not().assertUndefined(); + + }) + + /** + * @tc.number SUB_OBJECT_PROP_4500 + * @tc.name objectPropTest4500 + * @tc.desc test property name with Unicode characters + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest4500', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface UserData { + 中文属性: string; + éclairage : string; + } + const obj: UserData = { "中文属性" : "测试", "éclairage" : "light" } + expect(obj.中文属性).assertEqual("测试"); + expect(obj.éclairage).assertEqual("light"); + + }) + + /** + * @tc.number SUB_OBJECT_PROP_4600 + * @tc.name objectPropTest4600 + * @tc.desc test for...in loop includes inherited enumerable properties + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest4600', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + expect(objectPropTest4600()).assertEqual(2); // own + inherited + }) + + /** + * @tc.number SUB_OBJECT_PROP_4700 + * @tc.name objectPropTest4700 + * @tc.desc test hasOwnProperty returns false for inherited properties + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest4700', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + const result = objectPropTest4700() as boolean[]; + expect(result[0]).assertTrue(); + expect(result[1]).assertFalse(); + }) + + /** + * @tc.number SUB_OBJECT_PROP_4800 + * @tc.name objectPropTest4800 + * @tc.desc test modifying nested Object property value + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest4800', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface BaseData { + prop? : string; + } + interface UserData { + nested: BaseData; + } + const obj: UserData = { "nested" : { } } + obj.nested.prop = "old"; + obj.nested.prop = "new"; + expect(obj.nested.prop).assertEqual("new"); + + }) + + /** + * @tc.number SUB_OBJECT_PROP_4900 + * @tc.name objectPropTest4900 + * @tc.desc test reassigning nested Object reference + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest4900', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface BaseData { + prop : string; + } + interface UserData { + nested: BaseData; + } + const obj: UserData = { "nested" : { "prop" : "val" } } + obj.nested.prop = "val1"; + const oldNested = obj.nested; + expect(oldNested.prop).assertEqual("val1"); + obj.nested.prop = "val2"; + expect(obj.nested.prop).assertEqual("val2"); + + }) + /** + * @tc.number SUB_OBJECT_PROP_5000 + * @tc.name objectPropTest5000 + * @tc.desc object init use Record + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest5000', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const device: Electronic = { + brand: 'Apple', + price: 5999, + specs: { ['symId']: 'dev-001', ['symConfig']: '256GB' }, + objArr: [] + }; + + expect(device.brand).assertEqual('Apple'); + expect(device.specs!['symId']).assertEqual('dev-001'); + expect(device.specs!['symConfig']).assertEqual('256GB'); + + }); + + /** + * @tc.number SUB_OBJECT_PROP_5100 + * @tc.name objectPropTest5100 + * @tc.desc object prop + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest5100', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface Student{ + name: string; + scores: number[]; + } + interface ClassRoom{ + grade: string; + students: Student[]; + teachers: string[]; + } + const classroom: ClassRoom = { + grade: '3年级', + students: [ + { name: '张三', scores: [95, 88, 92] }, + { name: '李四', scores: [89, 91, 94] } + ], + teachers: ['王老师', '李老师'] + }; + + expect(classroom.grade).assertEqual('3年级'); + expect(classroom.students[0].scores[0]).assertEqual(95); + expect(classroom.teachers.length).assertEqual(2); + expect(classroom.students.filter(s => s.scores.includes(95)).length).assertEqual(1); + + }); + + /** + * @tc.number SUB_OBJECT_PROP_5200 + * @tc.name objectPropTest5200 + * @tc.desc object prop + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest5200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface Calculator{ + num1: number; + num2: number; + add?: ()=>number; + multiply?: ()=>number; + } + const calculator: Calculator = { + num1: 10, + num2: 20 + }; + calculator.add = () => calculator.num1 + calculator.num2; + calculator.multiply = () => calculator.num1 * calculator.num2; + + expect(calculator.add()).assertEqual(30); + expect(calculator.multiply()).assertEqual(200); + calculator.num1 = 15; + expect(calculator.add()).assertEqual(35); + + }); + + /** + * @tc.number SUB_OBJECT_PROP_5300 + * @tc.name objectPropTest5300 + * @tc.desc object prop + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest5300', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const user: User = {} as User; + user.id = 1001; + user.info = { name: 'Alice', email: 'alice@test.com' }; + + expect(user.id).assertEqual(1001); + expect(user.info.name).assertEqual('Alice'); + expect(user.info.email).assertEqual('alice@test.com'); + + }); + + /** + * @tc.number SUB_OBJECT_PROP_5400 + * @tc.name objectPropTest5400 + * @tc.desc object prop class in class + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest5400', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + class DateRange implements GeneratedTypeLiteralInterface_2{ + start: string; + end: string; + constructor(start: string, end: string) { + this.start = start; + this.end = end; + } + } + + const order: GeneratedObjectLiteralInterface_1 = { + orderId: 'ORD-001', + product: 'Laptop', + validPeriod: new DateRange('2024-01-01', '2024-12-31') + }; + + expect(order.orderId).assertEqual('ORD-001'); + expect(order.validPeriod.start).assertEqual('2024-01-01'); + expect(order.validPeriod.end).assertEqual('2024-12-31'); + + }); + + /** + * @tc.number SUB_OBJECT_PROP_5500 + * @tc.name objectPropTest5500 + * @tc.desc object prop use Object.create + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectPropTest5500', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + const toolBox = objectPropTest5500(); + expect(toolBox.name).assertEqual('Hand Tool Box'); + expect(toolBox.tools[0].weight).assertEqual('1kg'); + expect(toolBox.tools[1].use()).assertEqual('cut materials'); + + }); + + /** + * @tc.number SUB_OBJECT_PROP_5600 + * @tc.name objectPropTest5600 + * @tc.desc object prop default + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest5600', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + class Phone{ + brand: string; + model: string; + color: string; + constructor(brand: string, model: string, color: string = 'Black') { + this.brand = brand; + this.model = model; + this.color = color; + } + } + + const phone1 = new Phone('Samsung', 'S24'); + const phone2 = new Phone('Xiaomi', '14', 'White'); + + expect(phone1.color).assertEqual('Black'); + expect(phone2.color).assertEqual('White'); + expect(phone1.brand).assertEqual('Samsung'); + + }); + + /** + * @tc.number SUB_OBJECT_PROP_5700 + * @tc.name objectPropTest5700 + * @tc.desc object prop change + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectPropTest5700', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + class Counter{ + count: number; + constructor(count: number) { + this.count = count; + } + increment(step: number = 1) { + this.count += step; + } + reset(){ + this.count = 0; + } + } + + const counter = new Counter(5); + counter.increment(3); + expect(counter.count).assertEqual(8); + counter.reset(); + expect(counter.count).assertEqual(0); + + }); + + /** + * @tc.number SUB_OBJECT_PROP_5800 + * @tc.name objectPropTest5800 + * @tc.desc object prop static change + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectPropTest5800', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + class Product{ + static totalCount: number = 0; + name: string; + constructor(name: string) { + this.name = name; + Product.totalCount = (Product.totalCount || 0) + 1; + } + } + + Product.totalCount = 0; + + new Product('Shirt'); + new Product('Pants'); + new Product('Shoes'); + + expect(Product.totalCount).assertEqual(3); + + }); + + /** + * @tc.number SUB_OBJECT_PROP_5900 + * @tc.name objectPropTest5900 + * @tc.desc object prop change other prop + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectPropTest5900', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + class Address{ + city: string; + street: string; + constructor(city: string, street: string) { + this.city = city; + this.street = street; + } + } + class Customer{ + name: string; + address: Address; + constructor(name: string, address: Address) { + this.name = name; + this.address = address; + } + } + + const customer = new Customer('Bob', new Address('Guangzhou', 'Tianhe Rd')); + + expect(customer.name).assertEqual('Bob'); + expect(customer.address.city).assertEqual('Guangzhou'); + expect(customer.address.street).assertEqual('Tianhe Rd'); + + }); + + /** + * @tc.number SUB_OBJECT_PROP_6000 + * @tc.name objectPropTest6000 + * @tc.desc object prop Object.create + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectPropTest6000', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + interface UserData{ + a: number; + getA: ()=>number; + b?: number; + getB?: ()=>number; + c?: number; + getC?: ()=>number; + } + const grandparent: UserData = { a: 10, getA: () => grandparent.a }; + + const parent = objectPropTest6600(grandparent) as UserData; + parent.b = 20; + const child = objectPropTest6600(parent) as UserData; + child.c = 30; + child.getA = () => child.a; + child.getB = () => child.b!; + child.getC = () => child.c!; + + expect(child.a).assertEqual(10); + expect(child.getB!()).assertEqual(20); + expect(child.getC()).assertEqual(30); + expect(child.getA()).assertEqual(10); + + }); + + /** + * @tc.number SUB_OBJECT_PROP_6100 + * @tc.name objectPropTest6100 + * @tc.desc object prop Object.create can not delete prop + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectPropTest6100', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + interface BaseI{ + base?: string; + nonConfigurable?: string; + } + const obj = createObj() as BaseI; + + expect(obj.nonConfigurable).assertEqual('cannotDelete'); + expect(deleteNonConfigurable(obj)).assertFalse(); + expect(obj.nonConfigurable).assertEqual('cannotDelete'); + expect(deleteBase(obj)).assertEqual(true); + expect(obj.base).assertUndefined(); + + }); + + /** + * @tc.number SUB_OBJECT_PROP_6200 + * @tc.name objectPropTest6200 + * @tc.desc object prop Object.create override function + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectPropTest6200', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + const toolProto: Tool = { + type: 'Basic Tool', + use: () => 'use basic function' + }; + + const hammer = objectPropTest6600(toolProto) as Tool; + hammer.type = 'Hammer'; + hammer.use = () => 'drive nails'; + + const screwdriver = objectPropTest6600(toolProto) as Tool; + screwdriver.use = () => 'use basic function' + screwdriver.type = 'Screwdriver'; + + expect(hammer.use()).assertEqual('drive nails'); + expect(screwdriver.use()).assertEqual('use basic function'); + expect(hammer.type).assertEqual('Hammer'); + + }); + + /** + * @tc.number SUB_OBJECT_PROP_6300 + * @tc.name objectPropTest6300 + * @tc.desc object prop(NaN/Infinity) + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectPropTest6300', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL2, () => { + interface SpecialObj{ + nanVal: number; + infVal: number; + negInfVal: number; + isNan: (val: number) => boolean; + } + const specialObj: SpecialObj = { + nanVal: NaN, + infVal: Infinity, + negInfVal: -Infinity, + isNan: (val: number) => isNaN(val) + }; + + expect(isNaN(specialObj.nanVal)).assertEqual(true); + expect(specialObj.infVal).assertEqual(Infinity); + expect(specialObj.negInfVal).assertEqual(-Infinity); + expect(specialObj.isNan(specialObj.nanVal)).assertEqual(true); + + }); + + /** + * @tc.number SUB_OBJECT_PROP_6400 + * @tc.name objectPropTest6400 + * @tc.desc When testing the constructor without a new call, this points to (boundary scenario) + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectPropTest6400', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + class TestThis{ + name: string; + constructor(name: string) { + this.name = name; + } + } + + // use new + const testWithNew = new TestThis('Instance Test'); + expect(testWithNew.name).assertEqual('Instance Test'); + + }); + + /** + * @tc.number SUB_OBJECT_PROP_6500 + * @tc.name objectPropTest6500 + * @tc.desc Test Object. create creates an object that accesses non-existent prototype properties + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectPropTest6500', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface Proto{ + existProp: string; + nonExistProp?: object; + } + const proto: Proto = { existProp: 'value' }; + const obj = objectPropTest6600(proto) as Proto; + + expect(obj.existProp).assertEqual('value'); + expect(obj.nonExistProp).assertUndefined(); + + }); + + /** + * @tc.number SUB_OBJECT_PROP_6600 + * @tc.name objectPropTest6600 + * @tc.desc constructor+Object.create + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectPropTest6600', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + class Shop{ + name: string; + products: string[]; + addProduct: (product: string)=>void = (product: string)=>{this.products.push(product)} + constructor(name: string) { + this.name = name; + this.products =[]; + } + } + const techShop = new Shop('Tech Mall'); + + expect(techShop.name).assertEqual('Tech Mall'); + techShop.addProduct('Dell'); + expect(techShop.products.length).assertEqual(1); + + }); + + /** + * @tc.number SUB_OBJECT_PROP_6700 + * @tc.name objectPropTest6700 + * @tc.desc object init+constructor+Object.create + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectPropTest6700', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + class ConfigProto{ + theme: string; + fontSize: string; + constructor(theme: string, fontSize: string) { + this.theme = theme; + this.fontSize = fontSize; + } + updateFontSize(size: string){ + this.fontSize = size; + }; + } + const configProto = new ConfigProto('light', '16px'); + + class User{ + id: number; + name: string; + config: ConfigProto; + constructor(id: number, name: string) { + this.id = id; + this.name = name; + this.config = new ConfigProto(configProto.theme, configProto.fontSize); + } + } + + interface AppData{ + version: string; + activeUser: User; + lastUpdate: string; + } + const appData: AppData = { + version: 'v2.1.0', + activeUser: new User(101, 'Charlie'), + lastUpdate: '2024-05-01' + }; + + appData.activeUser.config.updateFontSize('14px'); + expect(appData.version).assertEqual('v2.1.0'); + expect(appData.activeUser.name).assertEqual('Charlie'); + expect(appData.activeUser.config.fontSize).assertEqual('14px'); + expect(appData.activeUser.config.theme).assertEqual('light'); + + }); + + /** + * @tc.number SUB_OBJECT_PROP_6800 + * @tc.name objectPropTest6800 + * @tc.desc 3 cases to create object + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectPropTest6800', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + class OrderItem{ + name: string; + price: number; + quantity: number; + constructor(name: string, price: number, quantity: number) { + this.name = name; + this.price = price; + this.quantity = quantity; + } + getTotal(): number{ + return this.price; + } + } + + interface OrderStatus{ + status: string; + updateStatus:(newStatus: string)=>void; + getStatusDesc: ()=>string; + } + const orderStatusProto: OrderStatus = { + status: 'pending', + updateStatus: (newStatus: string)=> { + orderStatusProto.status = newStatus; + }, + getStatusDesc: ()=> { + const descMap: Record = { ['pending']: '待支付', ['paid']: '已支付', ['shipped']: '已发货' }; + return descMap[orderStatusProto.status] || '未知状态'; + } + }; + + interface User{ + id: number; + name: string; + } + interface Order{ + orderId: string; + user: User; + items: OrderItem[]; + orderStatus: OrderStatus; + getOrderTotal: ()=>number; + } + const order: Order = { + orderId: 'ORD-20240501-001', + user: { id: 202, name: 'David' }, + items: [ + new OrderItem('Mouse', 29.9, 1), + new OrderItem('Keyboard', 99, 1) + ], + orderStatus: orderStatusProto, + getOrderTotal: ()=> { + return order.items.reduce((sum, item): number => sum + item.getTotal(), 0); + } + }; + + order.orderStatus.updateStatus('paid'); + const itemTotal = order.items[0].getTotal() + order.items[1].getTotal(); + + expect(order.orderId).assertEqual('ORD-20240501-001'); + expect(order.orderStatus.getStatusDesc()).assertEqual('已支付'); + expect(order.getOrderTotal()).assertEqual(itemTotal); + expect(order.getOrderTotal()).assertEqual(128.9); + }); + }) +} \ No newline at end of file diff --git a/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectCompare.js b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectCompare.js new file mode 100644 index 0000000000000000000000000000000000000000..b499b368b9e7e237621ab8120cc8f2a6e17ac176 --- /dev/null +++ b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectCompare.js @@ -0,0 +1,311 @@ +function deepClone(obj) { + if (obj === null || typeof obj !== 'object') { + return obj; + } + + if (Array.isArray(obj)) { + return obj.map(item => deepClone(item)); + } + + if (obj instanceof Date) { + return new Date(obj); + } + + if (obj instanceof RegExp) { + return new RegExp(obj.source, obj.flags); + } + + const cloned = {}; + Object.keys(obj).forEach(key => { + cloned[key] = deepClone(obj[key]); + }); + return cloned; +} + +export function objectCompareTest0800(){ + const obj = { value: 10 }; + const num = 10; + const str = "10"; + const objStr = new String("10"); + return [obj == num, num == str, num === str, num == objStr, objStr === str] +} +export function objectCompareTest0900(){ + const proto1 = { x: 10 }; + const proto2 = { x: 20 }; + + const obj1 = Object.create(proto1); + const obj2 = Object.create(proto2); + return [obj1, obj2] +} +export function objectCompareTest1300(){ + function Foo() { this.value = 1; } + function Bar() { this.value = 1; } + + const obj1 = new Foo(); + const obj2 = new Bar(); + return [obj1, obj2]; +} +export function objectCompareTest1400(){ + function Foo() { this.value = 1; } + + const obj1 = new Foo(); + const obj2 = new Foo(); + return [obj1, obj2]; +} +export function objectCompareTest1500(){ + const obj1 = { a: 1, b: "test" }; + const jsonStr = JSON.stringify(obj1); + const obj2 = JSON.parse(jsonStr); + return [obj1, obj2]; +} +export function objectCompareTest1600(){ + const numPrimitive = 100; + const numObject = new Number(100); + + return [numPrimitive, numObject]; +} +export function objectCompareTest1700(){ + const strPrimitive = "hello"; + const strObject = new String("hello"); + + return [strPrimitive, strObject]; +} +export function objectCompareTest1800(){ + const boolPrimitive = true; + const boolObject = new Boolean(true); + + return [boolPrimitive, boolObject]; +} +export function objectCompareTest1900(){ + const numPrimitive = 100; + const numObject = new Number(200); + + return [numPrimitive, numObject]; +} +export function objectCompareTest2000(){ + const obj = { a: 1 }; + const a = null; + + return [obj, a]; +} +export function objectCompareTest2100(){ + const obj = { a: 1 }; + const a = undefined; + + return [obj, a]; +} +export function objectCompareTest2200(){ + const num = 123; + const obj = new Number(123); + + return [num, obj.toString()]; +} +export function objectCompareTest2300(){ + const date1 = new Date(2023, 0, 1); + const date2 = new Date(2023, 0, 1); + const date3 = date1; + + return [date1, date2, date3]; +} +export function objectCompareTest2400(){ + const regex1 = /test/; + const regex2 = /test/; + const regex3 = regex1; + return [regex1, regex2, regex3]; +} +export function objectCompareTest2500(){ + const map1 = new Map(); + map1.set('a', 1); + + const map2 = new Map(); + map2.set('a', 1); + + const map3 = map1; + return [map1, map2, map3]; +} +export function objectCompareTest2600(){ + const set1 = new Set([1, 2, 3]); + const set2 = new Set([1, 2, 3]); + const set3 = set1; + return [set1, set2, set3]; +} +export function objectCompareTest2700(){ + const obj = { a: 1 }; + const arr = [1, 2, 3]; + const func = () => {}; + const date = new Date(); + + return [obj, arr, func, date]; +} +export function objectCompareTest2800(){ + class MyClass { + constructor(value) { + this.value = value; + } + } + + const instance1 = new MyClass(10); + const instance2 = new MyClass(10); + const instance3 = instance1; + return [instance1, instance2, instance3]; +} +export function objectCompareTest2900(){ + const arr = []; + const obj = {}; + + return [arr, obj]; +} +export function objectCompareTest3000(){ + const strObj = new String("test"); + const arr = ["t", "e", "s", "t"]; + + return [strObj, arr]; +} +export function objectCompareTest3100(){ + const obj1 = { a: { b: 1 } }; + const obj2 = { a: { b: 1 } }; + + return [obj1, obj2]; +} +export function objectCompareTest3200(){ + const obj1 = { a: { b: { c: { d: 1 } } } }; + const obj2 = { a: { b: { c: { d: 1 } } } }; + return [obj1, obj2]; +} +export function objectCompareTest3300(){ + const shared = { c: 3 }; + const obj1 = { a: 1, b: shared }; + const obj2 = { a: 1, b: shared }; + + return [obj1, obj2]; +} +export function objectCompareTest3400(){ + const obj1 = { a: [1, 2, 3] }; + const obj2 = { a: [1, 2, 3] }; + + return [obj1, obj2]; +} +export function objectCompareTest3500(){ + const obj1 = { a: () => {} }; + const obj2 = { a: () => {} }; + + return [obj1, obj2]; +} +export function objectCompareTest3600(){ + const obj1 = { a: { b: 1 } }; + const obj2 = obj1; + + return [obj1, obj2]; +} +export function objectCompareTest3700(obj1){ + obj1.a = { b: 2 }; +} +export function objectCompareTest3800(){ + const obj1 = { + a: 1, + b: "test", + c: { d: 2 }, + e: [3, 4], + f: () => 5 + }; + + const obj2 = { + a: 1, + b: "test", + c: { d: 2 }, + e: [3, 4], + f: () => 5 + }; + + return [obj1, obj2]; +} +export function objectCompareTest3900(){ + const obj1 = { a: 1 }; + obj1.self = obj1; // 循环引用 + + const obj2 = { a: 1 }; + obj2.self = obj2; // 另一个循环引用 + + const obj3 = obj1; + + return [obj1, obj2, obj3]; +} +export function objectCompareTest4000(){ + const original = { a: 1, b: { c: 2 } }; + const shallowCopy = { ...original }; + + return [original, shallowCopy]; +} +export function objectCompareTest4100(){ + const original = { a: 1, b: { c: 2 } }; + const copy = Object.assign({}, original); + + return [original, copy]; +} +export function objectCompareTest4200(){ + const original = { a: 1, b: { c: 2 }, d: [3, 4] }; + const deepCopy = deepClone(original); + + return [original, deepCopy]; +} +export function objectCompareTest4300(){ + const original = { a: 1, b: { c: 2 } }; + const shallowCopy = { ...original }; + + original.b.c = 3; + + return [original, shallowCopy]; +} +export function objectCompareTest4400(){ + const original = { a: 1, b: { c: 2 } }; + const deepCopy = deepClone(original); + + original.b.c = 3; + + return [original, deepCopy]; +} +export function objectCompareTest4500(){ + const obj1 = { a: 1 }; + const obj2 = obj1; + + return [obj1, obj2]; +} +export function objectCompareTest4501(obj1){ + obj1.a = 2; +} +export function objectCompareTest4600(){ + const obj1 = { a: { b: 1 } }; + const obj2 = obj1; + + return [obj1, obj2]; +} +export function objectCompareTest4601(obj1){ + obj1.a = { b: 2 }; +} +export function objectCompareTest4700(){ + const obj1 = { a: 1 }; + const obj2 = obj1; + + return [obj1, obj2]; +} +export function objectCompareTest4701(obj1){ + obj1.b = 2; +} +export function objectCompareTest4800(){ + const obj1 = { a: 1, b: 2 }; + const obj2 = obj1; + + return [obj1, obj2]; +} +export function objectCompareTest4801(obj1){ + delete obj1.b; +} +export function objectCompareTest4900(){ + const obj1 = { a: 1 }; + const obj2 = { a: 1 }; + Object.freeze(obj1); + Object.freeze(obj2); + const obj3 = obj1; + + return [obj1, obj2, obj3]; +} \ No newline at end of file diff --git a/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectCompare.test.ets b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectCompare.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..bd04ee5483e033ff2ca9dbdd70e92980852ef43e --- /dev/null +++ b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectCompare.test.ets @@ -0,0 +1,1017 @@ +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, TestType, Level, Size } from '@ohos/hypium'; +import { objectCompareTest0900, objectCompareTest0800, objectCompareTest1300, + objectCompareTest1400, + objectCompareTest1500, + objectCompareTest1600, + objectCompareTest1700, + objectCompareTest1800, + objectCompareTest1900, + objectCompareTest2000, + objectCompareTest2100, + objectCompareTest2200, + objectCompareTest2300, + objectCompareTest2400, + objectCompareTest2500, + objectCompareTest2600, + objectCompareTest2700, + objectCompareTest2800, + objectCompareTest2900, + objectCompareTest3000, + objectCompareTest3100, + objectCompareTest3200, + objectCompareTest3300, + objectCompareTest3400, + objectCompareTest3500, + objectCompareTest3600, + objectCompareTest3700, + objectCompareTest3800, + objectCompareTest3900, + objectCompareTest4000, + objectCompareTest4100, + objectCompareTest4200, + objectCompareTest4300, + objectCompareTest4400, + objectCompareTest4500, + objectCompareTest4501, + objectCompareTest4600, + objectCompareTest4601, + objectCompareTest4700, + objectCompareTest4701, + objectCompareTest4800, + objectCompareTest4801, + objectCompareTest4900} from './ObjectCompare'; + +function sleep(time: number): Promise { + return new Promise((re, je) => { + setTimeout(() => { + re(); + }, time); + }); +} + +interface ObjI{ + name?: string; + value?: number; +} + +export default function builtinsStatementObjectCompareTest() { + describe('builtinsStatementObjectCompareTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }) + beforeEach(async () => { + await sleep(100); + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }) + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }) + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }) + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_0100 + * @tc.name objectCompareTest0100 + * @tc.desc compare 2 object false + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectCompareTest0100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const obj1: ObjI = { name: "test", value: 10 }; + const obj2: ObjI = { name: "test", value: 10 }; + + expect(obj1 == obj2).assertFalse(); + expect(obj1 === obj2).assertFalse(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_0200 + * @tc.name objectCompareTest0200 + * @tc.desc objectCompareTest true + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectCompareTest0200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const obj1: ObjI = { name: "test" }; + const obj2 = obj1; + + expect(obj1 == obj2).assertTrue(); + expect(obj1 === obj2).assertTrue(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_0300 + * @tc.name objectCompareTest0300 + * @tc.desc object compare test + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectCompareTest0300', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const obj1: ObjI = { name: "test", value: 10 }; + const obj2 = obj1; + + obj1.value = 20; + + expect(obj1 == obj2).assertTrue(); + expect(obj1 === obj2).assertTrue(); + + expect(obj2.value).assertEqual(20); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_0400 + * @tc.name objectCompareTest0400 + * @tc.desc object compare test false + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectCompareTest0400', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + + class Person{ + name: string; + constructor(name: string) { + this.name = name; + } + } + + const person1 = new Person("Alice"); + const person2 = new Person("Alice"); + const person3 = person1; + + expect(person1 == person2).assertFalse(); + expect(person1 === person2).assertFalse(); + + expect(person1 == person3).assertTrue(); + expect(person1 === person3).assertTrue(); + }); + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_0500 + * @tc.name objectCompareTest0500 + * @tc.desc Compare the results of objects with different attribute orders but the same key value pairs + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectCompareTest0500', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface BaseI{ + a?: number; + b?: number; + } + const obj1: BaseI = { a: 1, b: 2 }; + const obj2: BaseI = { b: 2, a: 1 }; + + expect(obj1 == obj2).assertFalse(); + expect(obj1 === obj2).assertFalse(); + }); + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_0600 + * @tc.name objectCompareTest0600 + * @tc.desc Comparison of objects with different numbers of attributes + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectCompareTest0600', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface BaseI{ + a?: number; + b?: number; + } + const obj1: BaseI = { a: 1, b: 2 }; + const obj2: BaseI = { a: 1 }; + + expect(obj1 == obj2).assertFalse(); + expect(obj1 === obj2).assertFalse(); + }); + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_0700 + * @tc.name objectCompareTest0700 + * @tc.desc Comparison of objects with different prototypes + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectCompareTest0700', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface BaseI{ + x?: number; + } + const objArr = objectCompareTest0900() as BaseI[]; + expect(objArr[0] == objArr[1]).assertFalse(); + expect(objArr[0] === objArr[1]).assertFalse(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_0800 + * @tc.name objectCompareTest0800 + * @tc.desc Verify the behavioral differences between==and===in object and non object comparisons + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest0800', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + const obj: ObjI = { value: 10 }; + const num = 10; + const str = "10"; + const objStr = new String("10"); + + expect(objStr == str).assertTrue(); + expect(objStr === str).assertFalse(); + const resultObj = objectCompareTest0800(); + expect(resultObj[0]).assertFalse(); + expect(resultObj[1]).assertTrue(); + expect(resultObj[2]).assertFalse(); + + expect(resultObj[3]).assertTrue(); + expect(resultObj[4]).assertFalse(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_0900 + * @tc.name objectCompareTest0800 + * @tc.desc Comparison of objects with different prototypes + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectCompareTest0900', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface BaseI{ + x?: number; + } + const objArr = objectCompareTest0900() as BaseI[]; + expect(objArr[0] == objArr[1]).assertFalse(); + expect(objArr[0] === objArr[1]).assertFalse(); + }); + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_1000 + * @tc.name objectCompareTest1000 + * @tc.desc Validate the comparative properties of arrays as objects + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectCompareTest1000', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + // 内容相同的不同数组 + const arr1 = [1, 2, 3]; + const arr2 = [1, 2, 3]; + const arr3 = arr1; + + // 不同数组实例比较 + expect(arr1 == arr2).assertFalse(); + expect(arr1 === arr2).assertFalse(); + + // 同一数组引用比较 + expect(arr1 == arr3).assertTrue(); + expect(arr1 === arr3).assertTrue(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_1100 + * @tc.name objectCompareTest1100 + * @tc.desc Validate the comparative properties of functions as objects + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectCompareTest1100', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + let func = () => { + return 1; + } + let func1 = () => { + return 1; + } + + const func3 = func; + + expect(func == func1).assertFalse(); + expect(func === func1).assertFalse(); + + expect(func == func3).assertTrue(); + expect(func === func3).assertTrue(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_1200 + * @tc.name objectCompareTest1200 + * @tc.desc Verify the comparative characteristics of null and undefined + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectCompareTest1200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const a: null = null; + const b: undefined = undefined; + const c: null = null; + + expect(a == b).assertTrue(); + expect(a === b).assertFalse(); + + expect(a == c).assertTrue(); + expect(a === c).assertTrue(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_1300 + * @tc.name objectCompareTest1300 + * @tc.desc Comparison of Objects with Different Constructors + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest1300', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const funArr = objectCompareTest1300(); + expect(funArr[0] == funArr[1]).assertFalse(); + expect(funArr[0] === funArr[1]).assertFalse(); + }); + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_1400 + * @tc.name objectCompareTest1400 + * @tc.desc Comparison of different instances of the same constructor + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest1400', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const funArr = objectCompareTest1400(); + expect(funArr[0] == funArr[1]).assertFalse(); + expect(funArr[0] === funArr[1]).assertFalse(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_1500 + * @tc.name objectCompareTest1500 + * @tc.desc Comparison of objects that have been serialized/deserialized + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest1500', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const jsonArr = objectCompareTest1500() as object[]; + expect(jsonArr[0] == jsonArr[1]).assertFalse(); + expect(jsonArr[0] === jsonArr[1]).assertFalse(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_1600 + * @tc.name objectCompareTest1600 + * @tc.desc Comparison between numerical raw values and packaging objects + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest1600', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const numberArr = objectCompareTest1600(); + expect(numberArr[0] == numberArr[1]).assertTrue(); + expect(numberArr[0] === numberArr[1]).assertFalse(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_1700 + * @tc.name objectCompareTest1700 + * @tc.desc Comparison between string raw values and packaging objects + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest1700', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const stringArr = objectCompareTest1700(); + expect(stringArr[0] == stringArr[1]).assertTrue(); + expect(stringArr[0] === stringArr[1]).assertFalse(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_1800 + * @tc.name objectCompareTest1800 + * @tc.desc Comparison between boolean raw values and packaging objects + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest1800', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const booArr = objectCompareTest1800(); + expect(booArr[0] == booArr[1]).assertTrue(); + expect(booArr[0] === booArr[1]).assertFalse(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_1900 + * @tc.name objectCompareTest1900 + * @tc.desc Comparison between number values of different values and packaging objects + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest1900', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const numberArr = objectCompareTest1900(); + expect(numberArr[0] == numberArr[1]).assertFalse(); + expect(numberArr[0] === numberArr[1]).assertFalse(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_2000 + * @tc.name objectCompareTest2000 + * @tc.desc Comparison between null and object + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest2000', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const nullObjArr = objectCompareTest2000(); + expect(nullObjArr[0] == nullObjArr[1]).assertFalse(); + expect(nullObjArr[0] === nullObjArr[1]).assertFalse(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_2100 + * @tc.name objectCompareTest2100 + * @tc.desc Comparison between undefined and object + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest2100', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const undefinedObjArr = objectCompareTest2100(); + expect(undefinedObjArr[0] == undefinedObjArr[1]).assertFalse(); + expect(undefinedObjArr[0] === undefinedObjArr[1]).assertFalse(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_2200 + * @tc.name objectCompareTest2200 + * @tc.desc Comparison between raw value and object toString result + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest2200', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const toStringArr = objectCompareTest2200(); + expect(toStringArr[0] == toStringArr[1]).assertTrue(); + expect(toStringArr[0] === toStringArr[1]).assertFalse(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_2300 + * @tc.name objectCompareTest2300 + * @tc.desc Date Object Comparison + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest2300', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const dateArr = objectCompareTest2300(); + expect(dateArr[0] == dateArr[1]).assertFalse(); + expect(dateArr[0] === dateArr[1]).assertFalse(); + expect(dateArr[0] === dateArr[2]).assertTrue(); + + expect(dateArr[0].getTime() === dateArr[1].getTime()).assertTrue(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_2400 + * @tc.name objectCompareTest2400 + * @tc.desc Comparison of Regular Expressions + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest2400', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const regArr = objectCompareTest2400(); + + expect(regArr[0] == regArr[1]).assertFalse(); + expect(regArr[0] === regArr[1]).assertFalse(); + expect(regArr[0] === regArr[2]).assertTrue(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_2500 + * @tc.name objectCompareTest2500 + * @tc.desc Comparison of Map Expressions + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest2500', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const mapArr = objectCompareTest2500() as Map[]; + + expect(mapArr[0] == mapArr[1]).assertFalse(); + expect(mapArr[0] === mapArr[1]).assertFalse(); + expect(mapArr[0] === mapArr[2]).assertTrue(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_2600 + * @tc.name objectCompareTest2600 + * @tc.desc Comparison of Set Expressions + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest2600', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const setArr = objectCompareTest2600(); + + expect(setArr[0] == setArr[1]).assertFalse(); + expect(setArr[0] === setArr[1]).assertFalse(); + expect(setArr[0] === setArr[2]).assertTrue(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_2700 + * @tc.name objectCompareTest2700 + * @tc.desc Comparison of different types of objects + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest2700', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const differentArr = objectCompareTest2700(); + + expect(differentArr[0] == differentArr[1]).assertFalse(); + expect(differentArr[1] == differentArr[2]).assertFalse(); + expect(differentArr[2] == differentArr[3]).assertFalse(); + expect(differentArr[3] == differentArr[0]).assertFalse(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_2800 + * @tc.name objectCompareTest2800 + * @tc.desc Class instance comparison + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest2800', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const instanceArr = objectCompareTest2800(); + + expect(instanceArr[0] == instanceArr[1]).assertFalse(); + expect(instanceArr[0] === instanceArr[1]).assertFalse(); + expect(instanceArr[0] === instanceArr[2]).assertTrue(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_2900 + * @tc.name objectCompareTest2900 + * @tc.desc Comparison between empty arrays and empty objects + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest2900', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const differentArr = objectCompareTest2900(); + + expect(differentArr[0] == differentArr[1]).assertFalse(); + expect(differentArr[0] === differentArr[1]).assertFalse(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_3000 + * @tc.name objectCompareTest3000 + * @tc.desc Comparison between string objects and arrays + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest3000', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const stringAndArr = objectCompareTest3000(); + + expect(stringAndArr[0] == stringAndArr[1]).assertFalse(); + expect(stringAndArr[0] === stringAndArr[1]).assertFalse(); + + expect(stringAndArr[0] == stringAndArr[1]).assertFalse(); + expect(stringAndArr[0] === stringAndArr[1]).assertFalse(); + expect(stringAndArr[0].toString() == (stringAndArr[1] as string[]).join('')).assertTrue(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_3100 + * @tc.name objectCompareTest3100 + * @tc.desc Comparison of nested objects at the first level + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest3100', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const nestFirstArr = objectCompareTest3100(); + + expect(nestFirstArr[0] == nestFirstArr[1]).assertFalse(); + expect(nestFirstArr[0] === nestFirstArr[1]).assertFalse(); + expect(nestFirstArr[0].a == nestFirstArr[1].a).assertFalse(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_3200 + * @tc.name objectCompareTest3200 + * @tc.desc Comparison of nested objects at the two level + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest3200', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const nestTwoArr = objectCompareTest3100(); + + expect(nestTwoArr[0] == nestTwoArr[1]).assertFalse(); + expect(nestTwoArr[0] === nestTwoArr[1]).assertFalse(); + expect(nestTwoArr[0].a.b == nestTwoArr[1].a.b).assertTrue(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_3300 + * @tc.name objectCompareTest3300 + * @tc.desc Comparison of nested objects with partially shared references + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest3300', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const shareObjArr = objectCompareTest3300(); + + expect(shareObjArr[0] == shareObjArr[1]).assertFalse(); + expect(shareObjArr[0] === shareObjArr[1]).assertFalse(); + + expect(shareObjArr[0].b == shareObjArr[1].b).assertTrue(); + expect(shareObjArr[0].b === shareObjArr[1].b).assertTrue(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_3400 + * @tc.name objectCompareTest3400 + * @tc.desc Comparison of nested objects containing arrays + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest3400', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const nestArrArr = objectCompareTest3400(); + + expect(nestArrArr[0] == nestArrArr[1]).assertFalse(); + expect(nestArrArr[0] === nestArrArr[1]).assertFalse(); + expect(nestArrArr[0].a == nestArrArr[1].a).assertFalse(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_3500 + * @tc.name objectCompareTest3500 + * @tc.desc Comparison of nested objects containing functions + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest3500', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const nestFunArr = objectCompareTest3500(); + + expect(nestFunArr[0] == nestFunArr[1]).assertFalse(); + expect(nestFunArr[0] === nestFunArr[1]).assertFalse(); + expect(nestFunArr[0].a == nestFunArr[1].a).assertFalse(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_3600 + * @tc.name objectCompareTest3600 + * @tc.desc Comparison of nested object properties after modification + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest3600', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const nestChangeArr = objectCompareTest3600(); + + expect(nestChangeArr[0] === nestChangeArr[1]).assertTrue(); + expect(nestChangeArr[0].a === nestChangeArr[1].a).assertTrue(); + + nestChangeArr[0].a.b = 2; + + expect(nestChangeArr[0] === nestChangeArr[1]).assertTrue(); + expect(nestChangeArr[0].a === nestChangeArr[1].a).assertTrue(); + expect(nestChangeArr[1].a.b).assertEqual(2); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_3700 + * @tc.name objectCompareTest3700 + * @tc.desc Comparison after replacing nested objects + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest3700', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const nestChangeArr = objectCompareTest3600(); + + expect(nestChangeArr[0].a === nestChangeArr[1].a).assertTrue(); + + objectCompareTest3700(nestChangeArr[0]); + + expect(nestChangeArr[0] === nestChangeArr[1]).assertTrue(); + expect(nestChangeArr[0].a === nestChangeArr[1].a).assertTrue(); + expect(nestChangeArr[1].a.b).assertEqual(2); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_3800 + * @tc.name objectCompareTest3800 + * @tc.desc Comparison of mixed type nested objects + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest3800', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const mixedNestArr = objectCompareTest3800(); + + expect(mixedNestArr[0] == mixedNestArr[1]).assertFalse(); + expect(mixedNestArr[0] === mixedNestArr[1]).assertFalse(); + expect(mixedNestArr[0].c == mixedNestArr[1].c).assertFalse(); + expect(mixedNestArr[0].e == mixedNestArr[1].e).assertFalse(); + expect(mixedNestArr[0].f == mixedNestArr[1].f).assertFalse(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_3900 + * @tc.name objectCompareTest3900 + * @tc.desc Comparison of Circular Reference Objects + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest3900', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const circularObjArr = objectCompareTest3900(); + + expect(circularObjArr[0] == circularObjArr[1]).assertFalse(); + expect(circularObjArr[0] === circularObjArr[1]).assertFalse(); + expect(circularObjArr[0] === circularObjArr[2]).assertTrue(); + expect(circularObjArr[0].self === circularObjArr[2].self).assertTrue(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_4000 + * @tc.name objectCompareTest4000 + * @tc.desc Comparison of shallow copy objects + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest4000', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const shallowCopyArr = objectCompareTest4000(); + + expect(shallowCopyArr[0] == shallowCopyArr[1]).assertFalse(); + expect(shallowCopyArr[0] === shallowCopyArr[1]).assertFalse(); + + expect(shallowCopyArr[0].b == shallowCopyArr[1].b).assertTrue(); + expect(shallowCopyArr[0].b === shallowCopyArr[1].b).assertTrue(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_4100 + * @tc.name objectCompareTest4100 + * @tc.desc Object.assign copy compare + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest4100', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const assignCopyArr = objectCompareTest4100(); + + expect(assignCopyArr[0] == assignCopyArr[1]).assertFalse(); + expect(assignCopyArr[0] === assignCopyArr[1]).assertFalse(); + expect(assignCopyArr[0].b == assignCopyArr[1].b).assertTrue(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_4200 + * @tc.name objectCompareTest4200 + * @tc.desc Comparison of deep copy objects + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest4200', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + interface BaseI1{ + c: number; + } + interface BaseI2{ + a: number; + b: BaseI1; + d: number[]; + } + const deepCopyArr = objectCompareTest4200() as BaseI2[]; + + expect(deepCopyArr[0] == deepCopyArr[1]).assertFalse(); + expect(deepCopyArr[0] === deepCopyArr[1]).assertFalse(); + expect(deepCopyArr[0].b == deepCopyArr[1].b).assertFalse(); + expect(deepCopyArr[0].d == deepCopyArr[1].d).assertFalse(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_4300 + * @tc.name objectCompareTest4300 + * @tc.desc The impact of modifying the original object on shallow copies + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest4300', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const shallowCopyArr = objectCompareTest4300(); + + expect(shallowCopyArr[1].b.c).assertEqual(3); + expect(shallowCopyArr[0].b === shallowCopyArr[1].b).assertTrue(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_4400 + * @tc.name objectCompareTest4400 + * @tc.desc The impact of modifying the original object on deep copy + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest4400', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + interface BaseI1{ + c: number; + } + interface BaseI2{ + a: number; + b: BaseI1; + } + const deepCopyArr = objectCompareTest4400() as BaseI2[]; + + expect(deepCopyArr[1].b.c).assertEqual(2); + expect(deepCopyArr[0].b === deepCopyArr[1].b).assertFalse(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_4500 + * @tc.name objectCompareTest4500 + * @tc.desc Comparison of modified object properties + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest4500', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const modifiedArr = objectCompareTest4500(); + + expect(modifiedArr[0] === modifiedArr[1]).assertTrue(); + + objectCompareTest4501(modifiedArr[0]) + + expect(modifiedArr[0] === modifiedArr[1]).assertTrue(); + expect(modifiedArr[1].a).assertEqual(2); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_4600 + * @tc.name objectCompareTest4600 + * @tc.desc Comparison after replacing object attributes + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest4600', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const replaceArr = objectCompareTest4600(); + + expect(replaceArr[0] === replaceArr[1]).assertTrue(); + + objectCompareTest4601(replaceArr[0]) + + expect(replaceArr[0] === replaceArr[1]).assertTrue(); + expect(replaceArr[1].a.b).assertEqual(2); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_4700 + * @tc.name objectCompareTest4700 + * @tc.desc Comparison of objects after adding attributes + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest4700', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const addAttArr = objectCompareTest4700(); + + expect(addAttArr[0] === addAttArr[1]).assertTrue(); + + objectCompareTest4701(addAttArr[0]) + + expect(addAttArr[0] === addAttArr[1]).assertTrue(); + expect(addAttArr[1].b).assertEqual(2); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_4800 + * @tc.name objectCompareTest4800 + * @tc.desc Comparison of objects after deleting attributes + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest4800', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const delAttArr = objectCompareTest4800(); + + expect(delAttArr[0] === delAttArr[1]).assertTrue(); + + objectCompareTest4801(delAttArr[0]) + + expect(delAttArr[0] === delAttArr[1]).assertTrue(); + expect(delAttArr[1].b).assertUndefined(); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_4900 + * @tc.name objectCompareTest4900 + * @tc.desc Freeze object comparison + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest4900', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + const freezeObjArr = objectCompareTest4900(); + + expect(freezeObjArr[0] == freezeObjArr[1]).assertFalse(); + expect(freezeObjArr[0] === freezeObjArr[1]).assertFalse(); + expect(freezeObjArr[0] === freezeObjArr[2]).assertTrue(); + }); + + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_5000 + * @tc.name objectCompareTest5000 + * @tc.desc Validate the reference comparison feature of nested objects (non content comparison) + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectCompareTest5000', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL2, () => { + interface Base1{ + c: number; + } + interface Base2{ + a: number; + b: Base1; + } + interface Base3{ + x: Base2; + } + const nestedObj: Base2 = { a: 1, b: { c: 2 } }; + const obj1: Base3 = { x: nestedObj }; + const obj2: Base3 = { x: { a: 1, b: { c: 2 } } }; + const obj3 = obj1; + + expect(obj1 == obj2).assertFalse(); + expect(obj1 === obj2).assertFalse(); + expect(obj1 == obj3).assertTrue(); + + expect(obj1.x == obj2.x).assertFalse(); + expect(obj1.x == obj3.x).assertTrue(); + + nestedObj.a = 3; + expect(obj3.x.a).assertEqual(3); + }); + + /** + * @tc.number SUB_OBJECT_COMPARE_TEST_5100 + * @tc.name objectCompareTest5100 + * @tc.desc Comprehensive verification of various object comparison scenarios + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectCompareTest5100', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + interface Base{ + id: number; + } + const base: Base = { id: 1 }; + + const ref1 = base; + const ref2 = ref1; + + const newObj: Base = { id: 1 }; + + const arrBase = [1, 2, 3]; + const arrRef = arrBase; + const arrNew = [1, 2, 3]; + + expect(base == ref1).assertTrue(); + expect(ref1 === ref2).assertTrue(); + expect(arrBase == arrRef).assertTrue(); + + expect(base == newObj).assertFalse(); + expect(arrBase === arrNew).assertFalse(); + + ref2.id = 2; + expect(base.id).assertEqual(2); + expect(newObj.id).assertEqual(1); + + expect(null == undefined).assertTrue(); + expect(null === undefined).assertFalse(); + let arrA = []; + let arrB = []; + expect(arrA == arrB).assertFalse(); + }); + }); +} \ No newline at end of file diff --git a/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectExtends.js b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectExtends.js new file mode 100644 index 0000000000000000000000000000000000000000..43eff280ceee5fe6cf724f6edf18da330aca72b3 --- /dev/null +++ b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectExtends.js @@ -0,0 +1,30 @@ +export function objectExtendsTest1000(){ + const nullProtoObj = Object.create(null); + nullProtoObj.key = 'value'; + + return [nullProtoObj, Object.getPrototypeOf(nullProtoObj)] +} + +export function objectExtendsTest1500(proto){ + const obj = Object.create(proto); + obj.ownProp = 'own'; + return [obj.hasOwnProperty('ownProp'), obj.hasOwnProperty('inheritedProp'), obj.hasOwnProperty('nonExistProp')] +} + +export function objectExtendsTest1600(proto){ + const obj = Object.create(proto); + obj.own = 'ownVal'; + const nullProto = Object.create(null); + nullProto.key = 'val'; + return [Object.hasOwn(obj, 'own'), Object.hasOwn(obj, 'inherited'), Object.hasOwn(obj, 'nonExist'), Object.hasOwn(nullProto, 'key')] +} + +export function objectExtendsTest2200(proto1, proto2){ + const obj = Object.create(proto1); + + Object.setPrototypeOf(obj, proto2); + return obj; +} + +export function objectExtendsTest2600(){ +} \ No newline at end of file diff --git a/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectExtends.test.ets b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectExtends.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..719353307cd1484c9c322fcdcb53cc8e5d387f9a --- /dev/null +++ b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectExtends.test.ets @@ -0,0 +1,625 @@ + +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, TestType, Level, Size } from '@ohos/hypium'; +import { objectExtendsTest1000, objectExtendsTest1500, objectExtendsTest1600, + objectExtendsTest2200 } from './ObjectExtends'; + +// 定义通用接口确保类型安全 +interface ParentObj { + baseProp: string; + baseMethod: () => string; +} + +interface ChildObj extends ParentObj { + childProp?: string; +} + +interface ClassParent { + parentVal: number; + getParentVal: () => number; +} + +interface ClassChild extends ClassParent { + childVal: number; + getChildVal: () => number; +} + +class Circle { + radius: number; + + constructor(radios: number) { + this.radius = radios; + } + + getArea(): number { + return Math.PI * this.radius**2; + } +} + +function sleep(time: number): Promise { + return new Promise((re, je) => { + setTimeout(() => { + re(); + }, time); + }); +} + +export default function objectExtendsTest() { + describe('objectExtendsTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }) + beforeEach(async () => { + await sleep(100); + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }) + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }) + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }) + /** + * @tc.number SUB_OBJECT_EXTENDS_TEST_0100 + * @tc.name objectExtendsTest0100 + * @tc.desc Test single-layer prototype chain attribute lookup (instance → prototype) + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectExtendsTest0100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const proto: ParentObj = { baseProp: 'protoVal', baseMethod: () => 'protoMethod' }; + const instance = JSON.parse(JSON.stringify(proto)) as ParentObj; + instance.baseMethod = proto.baseMethod; + + expect(instance.baseProp).assertEqual('protoVal'); + expect(instance.baseMethod()).assertEqual('protoMethod'); + }); + + /** + * @tc.number SUB_OBJECT_EXTENDS_TEST_0200 + * @tc.name objectExtendsTest0200 + * @tc.desc Test multi-layer prototype chain attribute search (instance → prototype → prototype of prototype) + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectExtendsTest0200', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface Parent { + gProp?: string; + pProp?: string; + cProp?: string; + } + + const grandparent: Parent = { gProp: 'gVal' }; + const parent = JSON.parse(JSON.stringify(grandparent)) as Parent; + parent.pProp = 'pVal'; + const child = JSON.parse(JSON.stringify(parent)) as Parent; + child.cProp = 'cVal'; + + expect(child.cProp).assertEqual('cVal'); + expect(child.pProp).assertEqual('pVal'); + expect(child.gProp).assertEqual('gVal'); + + }); + + /** + * @tc.number SUB_OBJECT_EXTENDS_TEST_0300 + * @tc.name objectExtendsTest0300 + * @tc.desc When there is no attribute in the test prototype chain, return undefined + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectExtendsTest0300', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface Proto { + existProp?: string; + nonExistProp?: string; + nonExistMethod?: string; + } + + const proto: Proto = { existProp: 'existVal' }; + const instance = JSON.parse(JSON.stringify(proto)) as Proto; + + expect(instance.nonExistProp).assertUndefined(); + expect(instance.toString).not().assertUndefined(); + expect(instance.nonExistMethod).assertUndefined(); + + }); + + /** + * @tc.number SUB_OBJECT_EXTENDS_TEST_0400 + * @tc.name objectExtendsTest0400 + * @tc.desc When testing the new constructor, the instance [[Prototype]] points to prototype + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectExtendsTest0400', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + class Box { + value: number; + + constructor(value: number) { + this.value = value; + } + } + const box = new Box(10); + expect(box.constructor).assertEqual(Box); + }); + + /** + * @tc.number SUB_OBJECT_EXTENDS_TEST_0500 + * @tc.name objectExtendsTest0500 + * @tc.desc The prototype method of the test constructor is shared by all instances + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectExtendsTest0500', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + const circle1 = new Circle(2); + const circle2 = new Circle(3); + + expect(circle1.getArea).assertEqual(circle2.getArea); + expect(Math.round(circle1.getArea() * 100) / 100).assertEqual(12.57); + expect(Math.round(circle2.getArea() * 100) / 100).assertEqual(28.27); + + }); + + /** + * @tc.number SUB_OBJECT_EXTENDS_TEST_0600 + * @tc.name objectExtendsTest0600 + * @tc.desc Test constructor prototype chain inheritance (subclass prototype points to parent class prototype) + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectExtendsTest0600', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + class Parent { + name: string; + constructor(name: string) { + this.name = name + } + greet: () => string = () => { + return `Hello, ${this.name}`; + }; + } + + class Child extends Parent { + age: number; + constructor(name: string, age: number) { + super(name); + this.age = age; + } + getAge: () => number = () => { + return this.age; + } + } + + const child = new Child('Alice', 25); + expect(child.greet()).assertEqual('Hello, Alice'); + expect(child.getAge()).assertEqual(25); + + }); + + /** + * @tc.number SUB_OBJECT_EXTENDS_TEST_0700 + * @tc.name objectExtendsTest0700 + * @tc.desc Test Object. create to specify the prototype creation object + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectExtendsTest0700', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const proto: ParentObj = { baseProp: 'base', baseMethod: () => 'baseMethod' }; + const obj = JSON.parse(JSON.stringify(proto)) as ParentObj; + obj.baseMethod = () => 'baseMethod'; + obj.baseProp = 'override'; + + expect(obj.baseProp).assertEqual('override'); + expect(obj.baseMethod()).assertEqual('baseMethod'); + + }); + + /** + * @tc.number SUB_OBJECT_EXTENDS_TEST_0800 + * @tc.name objectExtendsTest0800 + * @tc.desc Test Object. create to create a null prototype object (without default inheritance) + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectExtendsTest0800', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + interface BaseI{ + key?: string; + } + const result = objectExtendsTest1000() as (Object | BaseI)[]; + expect(result[1]).assertNull(); + expect(result[0].toString).assertUndefined(); + expect(result[0].hasOwnProperty).assertUndefined(); + expect((result[0] as BaseI).key).assertEqual('value'); + + }); + + /** + * @tc.number SUB_OBJECT_EXTENDS_TEST_0900 + * @tc.name objectExtendsTest0900 + * @tc.desc Test Object. create combined with property descriptors to configure instance properties + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectExtendsTest0900', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + interface ReadOnlyProp { + value: string; + writable: boolean; + enumerable: boolean; + } + + interface NonEnumProp { + value: string; + enumerable: boolean; + } + + interface Proto { + protoProp?: string; + readOnlyProp?: ReadOnlyProp; + nonEnumProp?: NonEnumProp; + } + + const proto: Proto = { protoProp: 'protoVal' }; + const obj = JSON.parse(JSON.stringify(proto)) as Proto; + obj.readOnlyProp = { + value: 'fixed', + writable: false, + enumerable: true + }; + obj.nonEnumProp = { + value: 'hidden', + enumerable: false + } + + expect(obj.readOnlyProp.value).assertEqual('fixed'); + expect(obj.nonEnumProp.value).assertEqual('hidden'); + expect(obj.protoProp).assertEqual('protoVal'); + + }); + + /** + * @tc.number SUB_OBJECT_EXTENDS_TEST_1000 + * @tc.name objectExtendsTest1000 + * @tc.desc Test class extensions to implement basic class inheritance + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectExtendsTest1000', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + class ParentClass implements ClassParent { + parentVal: number; + + constructor(val: number) { + this.parentVal = val; + } + getParentVal() { + return this.parentVal; + } + } + + class ChildClass extends ParentClass implements ClassChild { + childVal: number; + constructor(parentVal: number, childVal: number) { + super(parentVal); + this.childVal = childVal; + } + getChildVal() { + return this.childVal; + } + } + + const child = new ChildClass(10, 20); + expect(child.getParentVal()).assertEqual(10); + expect(child.getChildVal()).assertEqual(20); + expect(child instanceof ParentClass).assertEqual(true); + expect(child instanceof ChildClass).assertEqual(true); + }); + + /** + * @tc.number SUB_OBJECT_EXTENDS_TEST_1100 + * @tc.name objectExtendsTest1100 + * @tc.desc Test the inheritance of static methods in class inheritance + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectExtendsTest1100', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + class Parent { + static staticMethod() { + return 'parentStatic'; + } + } + class Child extends Parent { + } + + expect(Parent.staticMethod()).assertEqual('parentStatic'); + expect(Child.staticMethod()).assertEqual('parentStatic'); + }); + + /** + * @tc.number SUB_OBJECT_EXTENDS_TEST_1200 + * @tc.name objectExtendsTest1200 + * @tc.desc Test sub object attribute masking prototype attribute + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectExtendsTest1200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface Proto { + prop: string; + method: () => string; + } + + const proto: Proto = { prop: 'protoVal', method: () => 'protoMethod' }; + const obj = JSON.parse(JSON.stringify(proto)) as Proto; + obj.method = () => 'protoMethod'; + obj.prop = 'objVal'; + obj.method = () => 'objMethod'; + + expect(obj.prop).assertEqual('objVal'); + expect(obj.method()).assertEqual('objMethod'); + expect(proto.prop).assertEqual('protoVal'); + }); + + /** + * @tc.number SUB_OBJECT_EXTENDS_TEST_1300 + * @tc.name objectExtendsTest1300 + * @tc.desc Test hasOwnProperty to check its own properties + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectExtendsTest1300', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface Proto{ + inheritedProp: string; + ownProp?: string; + } + const proto: Proto = { inheritedProp: 'inherited' }; + + const result = objectExtendsTest1500(proto) as boolean[]; + expect(result[0]).assertEqual(true); + expect(result[1]).assertEqual(false); + expect(result[2]).assertEqual(false); + }); + + /** + * @tc.number SUB_OBJECT_EXTENDS_TEST_1400 + * @tc.name objectExtendsTest1400 + * @tc.desc Test Object. hasOwn to check its own properties + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectExtendsTest1400', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface BaseI{ + inherited: string; + } + const proto: BaseI = { inherited: 'val' }; + + const result = objectExtendsTest1600(proto) as boolean[]; + expect(result[0]).assertEqual(true); + expect(result[1]).assertEqual(false); + expect(result[2]).assertEqual(false); + expect(result[3]).assertEqual(true); + }); + + /** + * @tc.number SUB_OBJECT_EXTENDS_TEST_1500 + * @tc.name objectExtendsTest1500 + * @tc.desc Test how modifying the constructor prototype affects existing instances + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectExtendsTest1500', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + class Dog { + name: string; + constructor(name: string) { + this.name = name; + } + bark: () => string = () => 'woof'; + } + + const dog = new Dog('Buddy'); + dog.bark = () => 'bow wow'; + expect(dog.bark()).assertEqual('bow wow'); + }); + + /** + * @tc.number SUB_OBJECT_EXTENDS_TEST_1600 + * @tc.name objectExtendsTest1600 + * @tc.desc Test that reassigning constructor prototype does not affect old instances + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectExtendsTest1600', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + interface Cat { + name: string; + meow: () => string; + } + + const oldCat: Cat = { + name: 'Mimi', + meow: () => 'meow' + }; + const newCat: Cat = { + name: 'Luna', + meow: () => 'mew' + }; + + expect(oldCat.meow()).assertEqual('meow'); + expect(newCat.meow()).assertEqual('mew'); + }); + + /** + * @tc.number SUB_OBJECT_EXTENDS_TEST_1700 + * @tc.name objectExtendsTest1700 + * @tc.desc In the test inheritance method, this points to an instance (non prototype) + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectExtendsTest1700', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface Proto { + value: number; + getValue: () => number; + } + + const proto: Proto = { + value: 10, + getValue: (): number => { + return proto.value; + } + }; + + const instance1 = JSON.parse(JSON.stringify(proto)) as Proto; + instance1.value = 20; + instance1.getValue = (): number => { + return instance1.value; + } + const instance2 = JSON.parse(JSON.stringify(proto)) as Proto; + instance2.value = 30; + instance2.getValue = (): number => { + return instance2.value; + } + + expect(instance1.getValue()).assertEqual(20); + expect(instance2.getValue()).assertEqual(30); + }); + + /** + * @tc.number SUB_OBJECT_EXTENDS_TEST_1800 + * @tc.name objectExtendsTest1800 + * @tc.desc When testing the arrow function as a prototype method, this points to the problem + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectExtendsTest1800', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + interface Proto { + value: number; + getValue: () => number; + } + + const proto: Proto = { + value: 10, + getValue: (): number => proto.value + }; + + const instance = JSON.parse(JSON.stringify(proto)) as Proto; + instance.getValue = (): number => instance.value + instance.value = 20; + + expect(instance.getValue()).assertEqual(20); + }); + + /** + * @tc.number SUB_OBJECT_EXTENDS_TEST_1900 + * @tc.name objectExtendsTest1900 + * @tc.desc Test Object. setPrototypeOf to modify existing object prototypes + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectExtendsTest1900', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + interface Proto1{ + prop1: string; + } + interface Proto2{ + prop2: string; + method2: ()=>string; + } + interface BaseI{ + prop1?: string; + prop2?: string; + method2?(): string; + } + const proto1: Proto1 = { prop1: 'val1' }; + const proto2: Proto2 = { prop2: 'val2', method2: () => 'method2' }; + const obj = objectExtendsTest2200(proto1, proto2) as BaseI; + + expect(obj.prop1).assertUndefined(); + expect(obj.prop2).assertEqual('val2'); + expect(obj.method2!()).assertEqual('method2'); + }); + + /** + * @tc.number SUB_OBJECT_EXTENDS_TEST_2000 + * @tc.name objectExtendsTest2000 + * @tc.desc Test the impact of dynamically adding prototype attributes on all instances + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectExtendsTest2000', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + class Product { + name: string; + constructor(name: string) { + this.name = name; + } + category?: string; + } + const p1 = new Product('Phone'); + const p2 = new Product('Laptop'); + + p1.category = 'Electronics'; + p2.category = 'Electronics'; + + expect(p1.category).assertEqual('Electronics'); + expect(p2.category).assertEqual('Electronics'); + }); + + /** + * @tc.number SUB_OBJECT_EXTENDS_TEST_2100 + * @tc.name objectExtendsTest2100 + * @tc.desc Test the inheritance of the Object. prototype method (such as toString) + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectExtendsTest2100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + interface BaseI { + a: number; + } + + const obj: BaseI = { a: 1 }; + const arr = [1, 2]; + const num = 123; + + expect(obj.toString()).assertEqual('[object Object]'); + expect(arr.toString()).assertEqual('1,2'); + expect(num.toString()).assertEqual('123'); + }); + + /** + * @tc.number SUB_OBJECT_EXTENDS_TEST_2200 + * @tc.name objectExtendsTest2200 + * @tc.desc Test the inheritance of the Functionality. prototype method (such as call/apply) + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectExtendsTest2200', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + let sum: (a: number, b: number) => number = (a: number, b: number) => { + return a + b; + } + + expect(sum(2, 3)).assertEqual(5); + expect(sum(4, 5)).assertEqual(9); + }); + }); +} \ No newline at end of file diff --git a/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectFunction.test.ets b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectFunction.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..10412c06a77c6d291cf521869e209fe8f478e063 --- /dev/null +++ b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectFunction.test.ets @@ -0,0 +1,350 @@ +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, TestType, Level, Size } from '@ohos/hypium'; + +interface Car { + make: string; + model: string; + year: number; + displayCar?: () => string; + record: Record; +} + +interface Calculator { + a: number; + b: number; + add?: () => number; + multiply?: () => number; +} + +function sleep(time: number): Promise { + return new Promise((re, je) => { + setTimeout(() => { + re(); + }, time); + }); +} + +export default function objectFunctionTest() { + describe('objectFunctionTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }) + beforeEach(async () => { + await sleep(100); + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }) + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }) + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }) + /** + * @tc.number SUB_OBJECT_FUNCTION_TEST_0100 + * @tc.name objectFunctionTest0100 + * @tc.desc Method for defining function expressions in test object literals + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectFunctionTest0100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const calculator: Calculator = { + a: 2, + b: 3, + add: (): number => { + return calculator.a + calculator.b; + } + }; + + expect(calculator.add).not().assertUndefined(); + expect(calculator.add!()).assertEqual(5); + }); + + /** + * @tc.number SUB_OBJECT_FUNCTION_TEST_0200 + * @tc.name objectFunctionTest0200 + * @tc.desc Method Abbreviation Grammar Definition Method in Test Object Literals + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectFunctionTest0200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const calculator: Calculator = { + a: 4, + b: 5, + multiply() { + return calculator.a * calculator.b; + } + }; + + expect(calculator.multiply).not().assertUndefined(); + expect(calculator.multiply!()).assertEqual(20); + }); + + /** + * @tc.number SUB_OBJECT_FUNCTION_TEST_0300 + * @tc.name objectFunctionTest0300 + * @tc.desc Test adding methods to objects dynamically + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectFunctionTest0300', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const car: Car = { + make: 'Toyota', + model: 'Camry', + year: 2023, + record: {} + }; + + let getCarAge = (car: Car) => { + const currentYear = new Date().getFullYear(); + return currentYear - car.year; + } + + car.record.getAge = getCarAge; + + expect(car.record.getAge).not().assertUndefined(); + expect(car.record.getAge(car)).assertEqual(new Date().getFullYear() - 2023); + + }); + + /** + * @tc.number SUB_OBJECT_FUNCTION_TEST_0400 + * @tc.name objectFunctionTest0400 + * @tc.desc Test defining methods in constructor + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectFunctionTest0400', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + class Car1{ + make: string; + model: string; + year: number; + constructor(make: string, model: string, year: number) { + this.make = make; + this.model = model; + this.year = year; + } + displayCar?: (car1: Car1)=>string = displayCar; + } + let displayCar = (car1: Car1) => { + return `A ${car1.year} ${car1.make} ${car1.model}`; + } + + const car1 = new Car1('Honda', 'Civic', 2022); + const car2 = new Car1('Ford', 'Mustang', 2024); + + expect(car1.displayCar!(car1)).assertEqual('A 2022 Honda Civic'); + expect(car2.displayCar!(car2)).assertEqual('A 2024 Ford Mustang'); + }); + + /** + * @tc.number SUB_OBJECT_FUNCTION_TEST_0500 + * @tc.name objectFunctionTest0500 + * @tc.desc In the testing method, this points to the calling object + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectFunctionTest0500', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface User{ + name: string; + age: number; + getUserInfo: ()=>string; + } + const user: User = { + name: 'Alice', + age: 30, + getUserInfo: (): string => { + return `Name: ${user.name}, Age: ${user.age}`; + } + }; + + expect(user.getUserInfo()).assertEqual('Name: Alice, Age: 30'); + + user.name = 'Bob'; + expect(user.getUserInfo()).assertEqual('Name: Bob, Age: 30'); + }); + + /** + * @tc.number SUB_OBJECT_FUNCTION_TEST_0600 + * @tc.name objectFunctionTest0600 + * @tc.desc Test the isolation of this when calling methods on different instances + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectFunctionTest0600', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, + () => { + class Product { + name: string; + price: number; + + constructor(name: string, price: number) { + this.name = name; + this.price = price; + } + + getPriceWithTax() { + return this.price * 1.1; // 10% tax + } + } + + const product1 = new Product('Laptop', 1000); + const product2 = new Product('Phone', 500); + + expect(product1.getPriceWithTax()).assertEqual(1100); + expect(product2.getPriceWithTax()).assertEqual(550); + + product1.price = 1200; + expect(product1.getPriceWithTax()).assertEqual(1320); + expect(product2.getPriceWithTax()).assertEqual(550); + + }); + + /** + * @tc.number SUB_OBJECT_FUNCTION_TEST_0700 + * @tc.name objectFunctionTest0700 + * @tc.desc Test the this difference between function calls and method calls + * @tc.size MediumTest + * @tc.type Function + * @level Level 2 + */ + it('objectFunctionTest0700', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + class Obj{ + value = 10; + getValue() { + return this ? this.value : undefined; + } + } + const obj = new Obj(); + + expect(obj.getValue()).assertEqual(10); + + const func = obj.getValue; + expect(func()).assertUndefined(); + + }); + + /** + * @tc.number SUB_OBJECT_FUNCTION_TEST_0800 + * @tc.name objectFunctionTest0800 + * @tc.desc When testing arrow functions as methods, this points to + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectFunctionTest0800', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + class Obj{ + value = 20; + getValue = () => this.value + } + const obj = new Obj(); + + expect(obj.getValue()).not().assertUndefined(); + }); + + /** + * @tc.number SUB_OBJECT_FUNCTION_TEST_0900 + * @tc.name objectFunctionTest0900 + * @tc.desc Inheritance and Call of Methods in the Test Prototype Chain + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectFunctionTest0900', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + class Animal{ + type: string; + constructor(type: string) { + this.type = type; + } + speak(){ + return `${this.type} makes a sound`; + } + } + + class Dog extends Animal{ + name: string; + constructor(name: string) { + super('dog'); + this.name = name; + } + speak(){ + return `${this.name} barks`; + } + } + + const animal = new Animal('cat'); + const dog = new Dog('Buddy'); + + expect(animal.speak()).assertEqual('cat makes a sound'); + expect(dog.speak()).assertEqual('Buddy barks'); + }); + + /** + * @tc.number SUB_OBJECT_FUNCTION_TEST_1000 + * @tc.name objectFunctionTest1000 + * @tc.desc Comprehensive scenario of testing method definition, invocation, and inheritance + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectFunctionTest1000', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + class BaseShape{ + color: string; + constructor(color: string) { + this.color = color; + } + getColor() { + return this.color; + } + } + const baseShape: BaseShape = new BaseShape('black'); + + class CirCle extends BaseShape{ + radius: number; + constructor(bashShape: BaseShape, raduis: number) { + super(bashShape.color); + this.radius = raduis; + } + getArea(){ + return Math.PI * this.radius**2; + } + } + const circle = new CirCle(baseShape, 5); + + class Rectangle{ + width: number; + height: number; + constructor(width: number, height: number) { + this.width = width; + this.height = height; + } + getArea(){ + return this.width * this.height; + } + setDimensions(width: number, height: number) { + this.width = width; + this.height = height; + } + } + + const rect = new Rectangle(4, 6); + + expect(circle.getColor()).assertEqual('black'); + expect(Math.round(circle.getArea() * 100) / 100).assertEqual(78.54); + + expect(rect.getArea()).assertEqual(24); + rect.setDimensions(5, 5); + expect(rect.getArea()).assertEqual(25); + }); + }); +} \ No newline at end of file diff --git a/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectGetSet.test.ets b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectGetSet.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..88aa906916aea2c8bd6ec15272a6848d0f1129a2 --- /dev/null +++ b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectGetSet.test.ets @@ -0,0 +1,344 @@ +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, TestType, Level, Size } from '@ohos/hypium'; + +interface GetterSetterObj { + a: number; + get b(): number; + set c(x: number); + record?: Record; +} + +interface ExtendedDate extends Date { + get year(): number; + set year(y: number); +} + +function sleep(time: number): Promise { + return new Promise((re, je) => { + setTimeout(() => { + re(); + }, time); + }); +} + +export default function objectGetSetTest() { + describe('objectGetSetTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }) + beforeEach(async () => { + await sleep(100); + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }) + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }) + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }) + /** + * @tc.number SUB_OBJECT_GET_SET_TEST_0100 + * @tc.name objectGetSetTest0100 + * @tc.desc Define Getter for testing object initialization and verify that the return value depends on the associated properties + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectGetSetTest0100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const obj: GetterSetterObj = { + a: 7, + get b() { + return obj.a + 1; + }, + set c(x: number) { + obj.a = x / 2; + } + }; + + expect(obj.b).assertEqual(8); + obj.a = 10; + expect(obj.b).assertEqual(11); + }); + + /** + * @tc.number SUB_OBJECT_GET_SET_TEST_0200 + * @tc.name objectGetSetTest0200 + * @tc.desc Define Setter for Test Object Initialize and verify the effect of modifying associated properties + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectGetSetTest0200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const obj: GetterSetterObj = { + a: 7, + get b() { + return obj.a + 1; + }, + set c(x: number) { + obj.a = x / 2; + } + }; + + obj.c = 50; + expect(obj.a).assertEqual(25); + expect(obj.b).assertEqual(26); + }); + + /** + * @tc.number SUB_OBJECT_GET_SET_TEST_0300 + * @tc.name objectGetSetTest0300 + * @tc.desc Test Object. FineProperty to define Getter separately + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectGetSetTest0300', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface ObjI{ + base: number; + get double(): number; + } + const obj: ObjI = { + base: 10, + get double(){ + return obj.base * 2; + } + }; + + expect(obj.double).assertEqual(20); + obj.base = 20; + expect(obj.double).assertEqual(40); + expect(Object.keys(obj)).assertContain('double'); + }); + + /** + * @tc.number SUB_OBJECT_GET_SET_TEST_0400 + * @tc.name objectGetSetTest0400 + * @tc.desc Test Object. FineProperty defines Getter/Setter and constrains configurable + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectGetSetTest0400', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface ObjI{ + count: number; + get adjust(): number; + set adjust(val: number); + } + const obj: ObjI = { + count: 10, + get adjust(){ + return obj.count; + }, + set adjust(val: number) { + obj.count = val > 0 ? val : 0; + } + }; + + obj.adjust = -5; + expect(obj.count).assertEqual(0); + obj.adjust = 15; + expect(obj.count).assertEqual(15); + expect(obj.adjust).assertEqual(15); + + }); + + /** + * @tc.number SUB_OBJECT_GET_SET_TEST_0500 + * @tc.name objectGetSetTest0500 + * @tc.desc Test Object. FineProperties Batch Define Getter/Setter + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectGetSetTest0500', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface ObjI{ + a: number; + get b(): number; + set c(x: number); + d?: string; + } + const obj: ObjI = { + a: 0, + get b() { + return obj.a + 1; + }, + set c(x: number) { + obj.a = x / 2; + }, + d: 'static' + }; + console.log(Object.keys(obj).toString()) + + obj.c = 10; + expect(obj.a).assertEqual(5); + expect(obj.b).assertEqual(6); + expect(obj.d).assertEqual('static'); + obj.d = 'updated'; + expect(obj.d).assertEqual('updated'); + expect(Object.keys(obj)).assertDeepEquals(['a', 'b', 'c', 'd']); + }); + + /** + * @tc.number SUB_OBJECT_GET_SET_TEST_0700 + * @tc.name objectGetSetTest0700 + * @tc.desc Test extended Date prototype, add year Getter/Setter + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectGetSetTest0700', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + class DateObj extends Date implements ExtendedDate{ + get year(): number { + return this.getFullYear(); + } + + set year(y: number) { + this.setFullYear(y); + } + } + + const now = new DateObj('2024-01-01') as ExtendedDate; + expect(now.year).assertEqual(2024); + now.year = 2025; + expect(now.getFullYear()).assertEqual(2025); + expect(now.toISOString().startsWith('2025')).assertEqual(true); + }); + + /** + * @tc.number SUB_OBJECT_GET_SET_TEST_0800 + * @tc.name objectGetSetTest0800 + * @tc.desc Getter/Setter inheritance for testing custom prototypes + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectGetSetTest0800', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + class ProductProto{ + price: number; + constructor(price: number) { + this.price = price; + } + get tax() { + return this.price * 0.1; + }; + set discount(rate: number) { + this.price = this.price * (1 - rate); + } + } + + const productProto: ProductProto = new ProductProto(100); + + const product1 = new ProductProto(productProto.price); + const product2 = new ProductProto(productProto.price); + + expect(product1.tax).assertEqual(10); + expect(product2.tax).assertEqual(10); + + product1.discount = 0.2; + expect(product1.price).assertEqual(80); + expect(product1.tax).assertEqual(8); + expect(product2.price).assertEqual(100); + }); + + /** + * @tc.number SUB_OBJECT_GET_SET_TEST_0900 + * @tc.name objectGetSetTest0900 + * @tc.desc Exception handling when testing Getter dependency attribute missing + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectGetSetTest0900', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + class ObjI{ + missingProp?: string; + get riskyGet(): string{ + return this.missingProp!.toUpperCase(); + } + } + const obj: ObjI = new ObjI(); + + expect(() => obj.riskyGet).assertThrowError(TypeError); + + obj.missingProp = 'test'; + expect(obj.riskyGet).assertEqual('TEST'); + }); + + /** + * @tc.number SUB_OBJECT_GET_SET_TEST_1000 + * @tc.name objectGetSetTest1000 + * @tc.desc Testing an uncountable Getter/Setter cannot be traversed through for... in + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectGetSetTest1000', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + class ObjI{ + visible: string; + constructor(visible: string) { + this.visible = visible; + } + get hiddenGet(){ + return 'hiddenValue'; + }; + set hiddenSet(val: string){ + this.visible = val; + } + } + const obj: ObjI = new ObjI('hello'); + + const enumeratedProps: string[] = []; + let strArr = Object.keys(obj) + for (let i = 0; i < strArr.length; i++) { + enumeratedProps.push(strArr[i]); + } + expect(enumeratedProps).assertDeepEquals(['visible']); + expect(obj.hiddenGet).assertEqual('hiddenValue'); + obj.hiddenSet = 'world'; + expect(obj.visible).assertEqual('world'); + }); + + /** + * @tc.number SUB_OBJECT_GET_SET_TEST_1100 + * @tc.name objectGetSetTest1100 + * @tc.desc Comprehensive testing defines Getter/Setter collaboration in multiple ways + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectGetSetTest1100', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + class Shop{ + basePrice: number; + discountAmount: number; + constructor(basePrice: number, discountAmount: number) { + this.basePrice = basePrice; + this.discountAmount = discountAmount; + } + get tax() { + return this.basePrice * 0.08; + } + get totalPrice() { + return this.basePrice + this.tax - this.discountAmount; + }; + set discount(rate: number){ + this.discountAmount = this.basePrice * rate; + } + } + const shop = new Shop(500, 0); + + expect(shop.totalPrice).assertEqual(540); + + shop.discount = 0.1; + expect(shop.discountAmount).assertEqual(50); + expect(shop.totalPrice).assertEqual(490); + + shop.basePrice = 600; + expect(shop.totalPrice).assertEqual(598); + }); + }); +} \ No newline at end of file diff --git a/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectIndex.test.ets b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectIndex.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..f79db575215acc364e84c3e5ac2aa7040adbdd82 --- /dev/null +++ b/commonlibrary/ets_utils/codeparsingtest/etsspectest/entry/src/ohosTest/ets/test/object/ObjectIndex.test.ets @@ -0,0 +1,268 @@ + +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, TestType, Level, Size } from '@ohos/hypium'; +// 定义通用类型 +interface NamedObject { + strArr: string[]; +} + +interface IndexedObject { + strArr: string[]; +} + +function sleep(time: number): Promise { + return new Promise((re, je) => { + setTimeout(() => { + re(); + }, time); + }); +} + +export default function objectIndexTest() { + describe('objectIndexTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }) + beforeEach(async () => { + await sleep(100); + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }) + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }) + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }) + /** + * @tc.number SUB_OBJECT_INDEX_TEST_0100 + * @tc.name objectIndexTest0100 + * @tc.desc The properties defined by the test name can only be accessed through the name + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectIndexTest0100', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const obj: Record = { ['name']: 'test', ['age']: 20 }; + + expect(obj.name).assertEqual('test'); + expect(obj['age']).assertEqual(20); + + expect(obj[0]).assertUndefined(); + expect(obj[1]).assertUndefined(); + }); + + /** + * @tc.number SUB_OBJECT_INDEX_TEST_0200 + * @tc.name objectIndexTest0200 + * @tc.desc The properties defined by the test index can only be accessed through the index + * @tc.size SmallTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectIndexTest0200', TestType.FUNCTION | Size.SMALLTEST | Level.LEVEL1, () => { + const obj: IndexedObject = { strArr: [] }; + obj.strArr[0] = 'first'; + obj.strArr[1] = 'second'; + + expect(obj.strArr[0]).assertEqual('first'); + expect(obj.strArr[1]).assertEqual('second'); + }); + + /** + * @tc.number SUB_OBJECT_INDEX_TEST_0300 + * @tc.name objectIndexTest0300 + * @tc.desc Test the attribute access constraints of mixed definition (name+index) + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectIndexTest0300', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface ExtendsI extends NamedObject, IndexedObject { + id?: string; + } + + const obj: ExtendsI = { + strArr: [] + }; + obj.id = '1001'; + obj.strArr[2] = 'value2'; + + expect(obj.id).assertEqual('1001'); + expect(obj.strArr[0]).assertUndefined(); + + expect(obj.strArr[2]).assertEqual('value2'); + }); + + /** + * @tc.number SUB_OBJECT_INDEX_TEST_0400 + * @tc.name objectIndexTest0400 + * @tc.desc Test that simulated HTML forms objects can be accessed by name and index + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectIndexTest0400', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + interface MockFrom { + name: string; + } + + const mockForm1: MockFrom = { name: 'userForm' }; + const mockForm2: MockFrom = { name: 'searchForm' }; + const forms = [mockForm1, mockForm2]; + forms['userForm'] = mockForm1; + forms['searchForm'] = mockForm2; + + expect(forms[0]).assertEqual(mockForm1); + expect(forms[1]).assertEqual(mockForm2); + + expect(forms['userForm']).assertEqual(mockForm1); + expect(forms['searchForm']).assertEqual(mockForm2); + + expect(forms[0]).assertEqual(forms['userForm']); + expect(forms[1]).assertEqual(forms['searchForm']); + }); + + /** + * @tc.number SUB_OBJECT_INDEX_TEST_0500 + * @tc.name objectIndexTest0500 + * @tc.desc Test that the properties added to the prototype are visible to all instances + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 1 + */ + it('objectIndexTest0500', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, () => { + class Book { + title: string; + + constructor(title: string) { + this.title = title; + } + author: string = 'unknown'; + } + + const book1 = new Book('JavaScript Guide'); + const book2 = new Book('TypeScript Handbook'); + + expect(book1.author).assertEqual('unknown'); + expect(book2.author).assertEqual('unknown'); + }); + + /** + * @tc.number SUB_OBJECT_INDEX_TEST_0600 + * @tc.name objectIndexTest0600 + * @tc.desc Testing that modifying the prototype property of a single instance does not affect other instances + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectIndexTest0600', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + class Animal { + type: string; + + constructor(type: string) { + this.type = type; + } + legs = 4; + } + + const dog = new Animal('dog'); + const bird = new Animal('bird'); + + dog.legs = 3; + + expect(dog.legs).assertEqual(3); + expect(bird.legs).assertEqual(4); // 仍使用原型默认值 + }); + + /** + * @tc.number SUB_OBJECT_INDEX_TEST_0700 + * @tc.name objectIndexTest0700 + * @tc.desc Test the impact of the prototype addition method on all instances + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectIndexTest0700', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + class Fruit { + name: string; + constructor(name: string) { + this.name = name; + } + getInfo():string{ + return `Fruit: ${this.name}` + } + } + + const apple = new Fruit('apple'); + const banana = new Fruit('banana'); + + expect(apple.getInfo()).assertEqual('Fruit: apple'); + expect(banana.getInfo()).assertEqual('Fruit: banana'); + expect(apple.getInfo).assertEqual(banana.getInfo); + }); + + /** + * @tc.number SUB_OBJECT_INDEX_TEST_0800 + * @tc.name objectIndexTest0800 + * @tc.desc Test the impact of modifying the prototype on existing instances + * @tc.size MediumTest + * @tc.type Function + * @tc.level Level 2 + */ + it('objectIndexTest0800', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL2, () => { + class Device { + brand: string; + + constructor(brand: string) { + this.brand = brand; + } + type?: string; + getType?: () => string | undefined; + } + + const phone = new Device('Apple'); + phone.type = 'electronic' + expect(phone.type).assertEqual('electronic'); + + phone.getType = (): string | undefined => { + return phone.type; + }; + expect(phone.getType()).assertEqual('electronic'); + }); + + /** + * @tc.number SUB_OBJECT_INDEX_TEST_0900 + * @tc.name objectIndexTest0900 + * @tc.desc Mixed scenario of testing attribute indexing rules and prototype extension + * @tc.size LargeTest + * @tc.type Function + * @tc.level Level 3 + */ + it('objectIndexTest0900', TestType.FUNCTION | Size.LARGETEST | Level.LEVEL3, () => { + class Product { + id: number; + + constructor(id: number) { + this.id = id + } + category = 'general'; + } + + const product = new Product(100); + expect(product.id).assertEqual(100); + expect(product.category).assertEqual('general'); + + product.category = 'electronics'; + expect(product.category).assertEqual('electronics'); + + const product2 = new Product(101); + expect(product2.category).assertEqual('general'); + }); + }); +}