• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include <cstddef>
17 #include <ctime>
18 #include <sys/time.h>
19 
20 #include "gtest/gtest.h"
21 
22 #include "assembler/assembly-parser.h"
23 #include "ecmascript/builtins/builtins.h"
24 #include "ecmascript/builtins/builtins_function.h"
25 #include "ecmascript/builtins/builtins_locale.h"
26 #include "ecmascript/compiler/aot_file/an_file_data_manager.h"
27 #include "ecmascript/compiler/aot_file/aot_file_manager.h"
28 #include "ecmascript/ecma_global_storage.h"
29 #include "ecmascript/ecma_vm.h"
30 #include "ecmascript/global_env.h"
31 #include "ecmascript/js_api/js_api_deque.h"
32 #include "ecmascript/js_api/js_api_queue.h"
33 #include "ecmascript/js_bigint.h"
34 #include "ecmascript/js_generator_object.h"
35 #include "ecmascript/js_list_format.h"
36 #include "ecmascript/js_runtime_options.h"
37 #include "ecmascript/js_thread.h"
38 #include "ecmascript/jspandafile/js_pandafile_manager.h"
39 #include "ecmascript/napi/include/jsnapi.h"
40 #include "ecmascript/napi/jsnapi_helper.h"
41 #include "ecmascript/object_factory.h"
42 #include "ecmascript/tagged_array.h"
43 #include "ecmascript/tests/test_helper.h"
44 
45 using namespace panda;
46 using namespace panda::ecmascript;
47 using namespace panda::pandasm;
48 using namespace panda::panda_file;
49 
50 namespace panda::test {
51 class JSNApiSampleTest : public testing::Test {
52 public:
SetUp()53     void SetUp() override
54     {
55         RuntimeOption option;
56         option.SetLogLevel(common::LOG_LEVEL::ERROR);
57         vm_ = JSNApi::CreateJSVM(option);
58         thread_ = vm_->GetJSThread();
59         vm_->SetEnableForceGC(true);
60     }
61 
TearDown()62     void TearDown() override
63     {
64         vm_->SetEnableForceGC(false);
65         JSNApi::DestroyJSVM(vm_);
66     }
67 
68 protected:
69     JSThread *thread_ = nullptr;
70     EcmaVM *vm_ = nullptr;
71 };
72 
73 /* demo1 原始类型的使用。 */
HWTEST_F_L0(JSNApiSampleTest,Sample_PrimitiveRef_IntegerRef)74 HWTEST_F_L0(JSNApiSampleTest, Sample_PrimitiveRef_IntegerRef)
75 {
76     LocalScope scope(vm_);
77     GTEST_LOG_(INFO) << "sample_primitive_IntegerRef_int=============================================================";
78     int inputInt = 123; // int value = 123
79     Local<IntegerRef> intObject = IntegerRef::New(vm_, inputInt);
80     int intValue = intObject->Value();
81     GTEST_LOG_(INFO) << "sample_primitive_IntegerRef_intValue : " << intValue;
82     Local<PrimitiveRef> pintObject = intObject;
83     GTEST_LOG_(INFO) << "sample_primitive_IntegerRef_pintObject_IsInt : " << pintObject->IsInt();
84     GTEST_LOG_(INFO) << "sample_primitive_IntegerRef_uint============================================================";
85     uint inputUint = 123; // uint value = 123
86     Local<IntegerRef> uintObject = IntegerRef::NewFromUnsigned(vm_, inputUint);
87     int uintValue = uintObject->Value();
88     GTEST_LOG_(INFO) << "sample_primitive_uintValue : " << uintValue;
89 }
90 
HWTEST_F_L0(JSNApiSampleTest,Sample_PrimitiveRef_NumberRef)91 HWTEST_F_L0(JSNApiSampleTest, Sample_PrimitiveRef_NumberRef)
92 {
93     LocalScope scope(vm_);
94     GTEST_LOG_(INFO) << "sample_primitive_NumberRef_double===========================================================";
95     double inputDouble = 3.14; // double value = 3.14
96     Local<NumberRef> doubleObject = NumberRef::New(vm_, inputDouble);
97     double doubleValue = doubleObject->Value();
98     GTEST_LOG_(INFO) << "sample_primitive_NumberRef_doubleValue : " << doubleValue;
99     Local<PrimitiveRef> pdoubleObject = doubleObject;
100     GTEST_LOG_(INFO) << "sample_primitive_NumberRef_pdoubleObject_IsNumber : " << pdoubleObject->IsNumber();
101     GTEST_LOG_(INFO) << "sample_primitive_NumberRef_int32_t==========================================================";
102     int32_t inputInt32t = 666; // int32-t value = 666
103     Local<NumberRef> int32tObject = NumberRef::New(vm_, inputInt32t);
104     double int32tValue = int32tObject->Value();
105     GTEST_LOG_(INFO) << "sample_primitive_NumberRef_int32tValue : " << int32tValue;
106     Local<PrimitiveRef> pint32tObject = int32tObject;
107     GTEST_LOG_(INFO) << "sample_primitive_NumberRef_pint32tObject_Int32Value : " << pint32tObject->Int32Value(vm_);
108     GTEST_LOG_(INFO) << "sample_primitive_NumberRef_uint32_t=========================================================";
109     uint32_t inputUint32t = 666; // uint32_t value = 666
110     Local<NumberRef> uint32tObject = NumberRef::New(vm_, inputUint32t);
111     double uint32tValue = uint32tObject->Value();
112     GTEST_LOG_(INFO) << "sample_primitive_NumberRef_uint32tValue : " << uint32tValue;
113     Local<PrimitiveRef> puint32tObject = uint32tObject;
114     GTEST_LOG_(INFO) << "sample_primitive_NumberRef_puint32tObject_Uint32Value : " << puint32tObject->Uint32Value(vm_);
115     GTEST_LOG_(INFO) << "sample_primitive_NumberRef_int64_t==========================================================";
116     int64_t inputInt64t = 666; // int64_t value = 666
117     Local<NumberRef> int64tObject = NumberRef::New(vm_, inputInt64t);
118     double int64tValue = int64tObject->Value();
119     GTEST_LOG_(INFO) << "sample_primitive_NumberRef_int64tValue : " << int64tValue;
120 }
121 
HWTEST_F_L0(JSNApiSampleTest,Sample_PrimitiveRef_BigIntRef_Uint64)122 HWTEST_F_L0(JSNApiSampleTest, Sample_PrimitiveRef_BigIntRef_Uint64)
123 {
124     LocalScope scope(vm_);
125     GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_uint64_t=========================================================";
126     uint64_t inputUint64t = 999; // uint64_t value = 999
127     Local<BigIntRef> uint64tObject = BigIntRef::New(vm_, inputUint64t);
128     int64_t ucValue = 0;
129     bool uLossless = true;
130     uint64_t ucValue1 = 0;
131     uint64tObject->BigIntToInt64(vm_, &ucValue, &uLossless);
132     GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_BigIntToInt64 : " << ucValue;
133     uint64tObject->BigIntToUint64(vm_, &ucValue1, &uLossless);
134     GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_BigIntToUint64 : " << ucValue1;
135     bool uSign = false;
136     uint32_t uSize = 3;
137     int uarraySize = 3;
138     const uint64_t uWords[3] = {666, 777, 888};
139     Local<JSValueRef> ubigWords = BigIntRef::CreateBigWords(vm_, uSign, uSize, uWords);
140     for (int i = 0; i < uarraySize; i++) {
141         GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_UwordsArrayindex"
142                          << " [ " << i << " ] : " << uWords[i];
143     }
144     Local<BigIntRef> ubigWordsRef(ubigWords);
145     GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_UArraySize : " << ubigWordsRef->GetWordsArraySize(vm_);
146     bool uresultSignBit = true;
147     int unewarraySize = 3;
148     uint64_t *uresultWords = new uint64_t[unewarraySize]();
149     ubigWordsRef->GetWordsArray(vm_, &uresultSignBit, uSize, uresultWords);
150     for (int i = 0; i < unewarraySize; i++) {
151         GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_uresultWords"
152                          << " [ " << i << " ] : " << uresultWords[i];
153     }
154 }
155 
HWTEST_F_L0(JSNApiSampleTest,Sample_PrimitiveRef_BigIntRef_Int64)156 HWTEST_F_L0(JSNApiSampleTest, Sample_PrimitiveRef_BigIntRef_Int64)
157 {
158     LocalScope scope(vm_);
159     GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_int64_t==========================================================";
160     int64_t inputInt64t = 111; // int64_t value = 111
161     Local<BigIntRef> int64tObject = BigIntRef::New(vm_, inputInt64t);
162     int64_t icValue = 0;
163     bool iLossless = true;
164     uint64_t icValue1 = 0;
165     int64tObject->BigIntToInt64(vm_, &icValue, &iLossless);
166     GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_BigIntToInt64 : " << icValue;
167     int64tObject->BigIntToUint64(vm_, &icValue1, &iLossless);
168     GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_BigIntToUint64 : " << icValue1;
169     bool iSign = false;
170     uint32_t iSize = 3;
171     int iarraySize = 3;
172     const uint64_t iWords[3] = {222, 333, 444};
173     Local<JSValueRef> ibigWords = BigIntRef::CreateBigWords(vm_, iSign, iSize, iWords);
174     for (int i = 0; i < iarraySize; i++) {
175         GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_iWordsArrayindex"
176                          << " [ " << i << " ] : " << iWords[i];
177     }
178     Local<BigIntRef> ibigWordsRef(ibigWords);
179     GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_iarraySize : " << ibigWordsRef->GetWordsArraySize(vm_);
180     bool iresultSignBit = true;
181     int inewarraySize = 3;
182     uint64_t *iresultWords = new uint64_t[inewarraySize]();
183     ibigWordsRef->GetWordsArray(vm_, &iresultSignBit, iSize, iresultWords);
184     for (int i = 0; i < inewarraySize; i++) {
185         GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_iresultWords"
186                          << " [ " << i << " ] : " << iresultWords[i];
187     }
188     Local<PrimitiveRef> pint64tObject = int64tObject;
189     GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_pint64tObject_IsBigInt : " << pint64tObject->IsBigInt(vm_);
190 }
191 
HWTEST_F_L0(JSNApiSampleTest,Sample_PrimitiveRef_BooleanRef)192 HWTEST_F_L0(JSNApiSampleTest, Sample_PrimitiveRef_BooleanRef)
193 {
194     LocalScope scope(vm_);
195     GTEST_LOG_(INFO) << "sample_primitive_BooleanRef_true============================================================";
196     Local<BooleanRef> trueObject = BooleanRef::New(vm_, true);
197     GTEST_LOG_(INFO) << "sample_primitive_BooleanRef_trueObject_Value : " << trueObject->Value();
198     Local<PrimitiveRef> ptrueObject = trueObject;
199     GTEST_LOG_(INFO) << "sample_primitive_BooleanRef_ptrueObject_IsBoolean : " << ptrueObject->IsBoolean();
200     GTEST_LOG_(INFO) << "sample_primitive_BooleanRef_false===========================================================";
201     Local<BooleanRef> falseObject = BooleanRef::New(vm_, false);
202     GTEST_LOG_(INFO) << "sample_primitive_BooleanRef_falseObject_Value : " << falseObject->Value();
203     Local<PrimitiveRef> pfalseObject = falseObject;
204     GTEST_LOG_(INFO) << "sample_primitive_BooleanRef_pfalseObject_IsBoolean : " << pfalseObject->IsBoolean();
205 }
206 
HWTEST_F_L0(JSNApiSampleTest,Sample_PrimitiveRef_StringRef_Char)207 HWTEST_F_L0(JSNApiSampleTest, Sample_PrimitiveRef_StringRef_Char)
208 {
209     LocalScope scope(vm_);
210     GTEST_LOG_(INFO) << "sample_primitive_StringRef_char=============================================================";
211     char utf8[12] = "Hello world";
212     Local<JSValueRef> local = StringRef::NewFromUtf8(vm_, utf8);
213     JSValueRef *jsValue = (*local);
214     StringRef *charObject = StringRef::Cast(jsValue);
215     EXPECT_EQ(charObject->Utf8Length(vm_), 12);
216     char buffer[12];
217     EXPECT_EQ(charObject->WriteUtf8(vm_, buffer, 12), 12);
218     std::string res(buffer);
219     GTEST_LOG_(INFO) << "sample_primitive_StringRef_charObject : " << res;
220     std::string charObjectStr = charObject->ToString(vm_);
221     GTEST_LOG_(INFO) << "sample_primitive_StringRef_charObject_ToString : " << charObjectStr;
222     uint32_t charSize = charObject->Length(vm_);
223     GTEST_LOG_(INFO) << "sample_primitive_StringRef_charObject_Length : " << charSize;
224     char cs[16] = {0};
225     uint32_t length = charObject->WriteLatin1(vm_, cs, 12);
226     GTEST_LOG_(INFO) << "sample_primitive_StringRef_charObject_WriteLatin1 : " << length;
227     Local<StringRef> napiWrapperString = charObject->GetNapiWrapperString(vm_);
228     EXPECT_EQ(napiWrapperString->Utf8Length(vm_), 13);
229     char buffer1[12];
230     EXPECT_EQ(charObject->WriteUtf8(vm_, buffer1, 12), 12);
231     std::string res1(buffer1);
232     GTEST_LOG_(INFO) << "sample_primitive_StringRef_charObject_GetNapiWrapperString : " << res1;
233     PrimitiveRef *pcharObject = charObject;
234     GTEST_LOG_(INFO) << "sample_primitive_StringRef_pcharObject_IsString : " << pcharObject->IsString(vm_);
235 }
236 
HWTEST_F_L0(JSNApiSampleTest,Sample_PrimitiveRef_StringRef_Char16)237 HWTEST_F_L0(JSNApiSampleTest, Sample_PrimitiveRef_StringRef_Char16)
238 {
239     LocalScope scope(vm_);
240     GTEST_LOG_(INFO) << "sample_primitive_StringRef_char16_t=========================================================";
241     const char16_t *utf16 = u"Hi,ABCDEF";
242     Local<JSValueRef> local = StringRef::NewFromUtf16(vm_, utf16);
243     JSValueRef *jsValue = (*local);
244     StringRef *char16tObject = StringRef::Cast(jsValue);
245     EXPECT_EQ(char16tObject->Utf8Length(vm_), 10);
246     char16_t buffer2[10];
247     EXPECT_EQ(char16tObject->WriteUtf16(vm_, buffer2, 9), 9);
248     std::string res2(buffer2, buffer2 + sizeof(buffer2) / sizeof(char16_t));
249     GTEST_LOG_(INFO) << "sample_primitive_StringRef_char16tObject : " << res2 << std::endl;
250     std::string char16tObjectStr = char16tObject->ToString(vm_);
251     GTEST_LOG_(INFO) << "sample_primitive_StringRef_char16tObject_ToString : " << char16tObjectStr;
252     uint32_t charSize = char16tObject->Length(vm_);
253     GTEST_LOG_(INFO) << "sample_primitive_StringRef_char16tObject_Length : " << charSize;
254     char cs1[10] = {0};
255     uint32_t length = char16tObject->WriteLatin1(vm_, cs1, 10);
256     GTEST_LOG_(INFO) << "sample_primitive_StringRef_char16tObject_WriteLatin1 : " << length;
257     Local<StringRef> napiWrapperString = char16tObject->GetNapiWrapperString(vm_);
258     EXPECT_EQ(napiWrapperString->Utf8Length(vm_), 13);
259     char16_t buffer3[10];
260     EXPECT_EQ(char16tObject->WriteUtf16(vm_, buffer3, 9), 9);
261     std::string res3(buffer3, buffer3 + sizeof(buffer3) / sizeof(char16_t));
262     GTEST_LOG_(INFO) << "sample_primitive_StringRef_char16tObject : " << res3;
263     PrimitiveRef *pchar16tObject = char16tObject;
264     GTEST_LOG_(INFO) << "sample_primitive_StringRef_pchar16tObject_IsString : " << pchar16tObject->IsString(vm_);
265 }
266 
267 /**
268  * trap for isCompress, notify cj if modify
269  */
HWTEST_F_L0(JSNApiSampleTest,Sample_PrimitiveRef_StringRef_IsCompress)270 HWTEST_F_L0(JSNApiSampleTest, Sample_PrimitiveRef_StringRef_IsCompress)
271 {
272     {
273         LocalScope scope(vm_);
274         const char16_t * cases[] {
275             u"a plain text, 和",
276             u"你好,世界!",
277             u"����",
278         };
279         constexpr auto bufferSize = 128;
280         char16_t buffer[bufferSize] {0};
281         for (auto one : cases) {
282             std::u16string src = one;
283             auto string = StringRef::NewFromUtf16WithoutStringTable(vm_, one, src.size());
284             EXPECT_FALSE(string->IsCompressed(vm_));
285             EXPECT_EQ(string->Length(vm_), src.size());
286             auto writeSize = string->WriteUtf16(vm_, buffer, bufferSize);
287             EXPECT_EQ(writeSize, src.size());
288             std::u16string res(buffer, writeSize);
289             EXPECT_EQ(src, res);
290         }
291     }
292     {
293         LocalScope scope(vm_);
294         std::string utf16Cases[] {
295             "a plain text, 和",
296             "你好,世界!",
297             "����",
298         };
299         std::string latin1Cases[] {
300             "this is a plain text",
301             "123,./;'",
302             ""
303         };
304         for (const auto& one: utf16Cases) {
305             auto string = StringRef::NewFromUtf8(vm_, one.c_str(), one.size());
306             EXPECT_FALSE(string->IsCompressed(vm_));
307         }
308         for (const auto& one : latin1Cases) {
309             auto string = StringRef::NewFromUtf8(vm_, one.c_str(), one.size());
310             EXPECT_TRUE(string->IsCompressed(vm_));
311         }
312     }
313 }
314 
HWTEST_F_L0(JSNApiSampleTest,Sample_PrimitiveRef_SymbolRef)315 HWTEST_F_L0(JSNApiSampleTest, Sample_PrimitiveRef_SymbolRef)
316 {
317     LocalScope scope(vm_);
318     GTEST_LOG_(INFO) << "sample_primitive_SymbolRef==================================================================";
319     Local<SymbolRef> symbolObject = SymbolRef::New(vm_, StringRef::NewFromUtf8(vm_, "description"));
320     Local<StringRef> symbolDescription = symbolObject->GetDescription(vm_);
321     GTEST_LOG_(INFO) << "sample_primitive_symbol_description : " << symbolDescription->ToString(vm_);
322     Local<PrimitiveRef> psymbolObject = symbolObject;
323     GTEST_LOG_(INFO) << "sample_primitive_SymbolRef_Psym_IsSymbol : " << psymbolObject->IsSymbol(vm_);
324 }
325 
326 /* demo2 本地指针包装的使用。 */
327 class NativePointerTestClass {
328 public:
NativePointerTestClass()329     NativePointerTestClass() : someProperty(0)
330     {
331         GTEST_LOG_(INFO) << "NativePointerTestClass Construction";
332     }
333 
~NativePointerTestClass()334     ~NativePointerTestClass()
335     {
336         GTEST_LOG_(INFO) << "NativePointerTestClass Destruction";
337     }
338 
GetsomeProperty() const339     int GetsomeProperty() const
340     {
341         return someProperty;
342     }
343 
SetsomeProperty(int value)344     void SetsomeProperty(int value)
345     {
346         someProperty = value;
347     }
348 
349 private:
350     int someProperty;
351 };
352 
HWTEST_F_L0(JSNApiSampleTest,sample_NativePointerRef)353 HWTEST_F_L0(JSNApiSampleTest, sample_NativePointerRef)
354 {
355     LocalScope scope(vm_);
356     NativePointerTestClass *nativePointerTestClass = new NativePointerTestClass();
357     GTEST_LOG_(INFO) << "sample_NativePointer adress: " << nativePointerTestClass;
358     Local<NativePointerRef> nativePoint = NativePointerRef::New(
359         vm_, nativePointerTestClass,
360         [](void *env, void *value, void *hint) {
361             GTEST_LOG_(INFO) << "NativePointerCb value : " << value;
362             GTEST_LOG_(INFO) << "NativePointerCb hint  : " << hint;
363             NativePointerTestClass *ptr = static_cast<NativePointerTestClass *>(value);
364             delete ptr;
365         },
366         (void *)0x123);
367     NativePointerTestClass *yourClassPtr = static_cast<NativePointerTestClass *>(nativePoint->Value());
368     GTEST_LOG_(INFO) << "sample_NativePointer GetValue : " << yourClassPtr->GetsomeProperty();
369     yourClassPtr->SetsomeProperty(99);
370     GTEST_LOG_(INFO) << "sample_NativePointer SetValue : " << yourClassPtr->GetsomeProperty();
371     GTEST_LOG_(INFO) << "sample_NativePointer Value : " << nativePoint->Value();
372 }
373 
HWTEST_F_L0(JSNApiSampleTest,sample_NativePointerRef_String)374 HWTEST_F_L0(JSNApiSampleTest, sample_NativePointerRef_String)
375 {
376     LocalScope scope(vm_);
377     void *vps = new std::string("123456");
378     Local<NativePointerRef> nativePoint = NativePointerRef::New(vm_, vps);
379     std::string *p = (std::string *)nativePoint->Value();
380     GTEST_LOG_(INFO) << "sample_NativePointerRef_String Value : " << *p;
381     std::string value = "78910";
382     *p = value;
383     GTEST_LOG_(INFO) << "sample_NativePointerRef_String ChangeValue : " << *((std::string *)nativePoint->Value());
384 }
385 
HWTEST_F_L0(JSNApiSampleTest,sample_NativePointerRef_Double)386 HWTEST_F_L0(JSNApiSampleTest, sample_NativePointerRef_Double)
387 {
388     LocalScope scope(vm_);
389     void *vpd = new double(123.456);
390     Local<NativePointerRef> nativePoint = NativePointerRef::New(vm_, vpd);
391     double *p = (double *)nativePoint->Value();
392     GTEST_LOG_(INFO) << "sample_NativePointerRef_Double Value : " << *p;
393     double value = 66.66;
394     *p = value;
395     GTEST_LOG_(INFO) << "sample_NativePointerRef_Double ChangeValue: " << *((double *)nativePoint->Value());
396 }
397 
HWTEST_F_L0(JSNApiSampleTest,sample_NativePointerRef_Char)398 HWTEST_F_L0(JSNApiSampleTest, sample_NativePointerRef_Char)
399 {
400     LocalScope scope(vm_);
401     void *vpc = new char('a');
402     Local<NativePointerRef> nativePoint = NativePointerRef::New(vm_, vpc);
403     char *p = (char *)nativePoint->Value();
404     GTEST_LOG_(INFO) << "sample_NativePointerRef_Char Value : " << *p;
405     *p = 'A';
406     GTEST_LOG_(INFO) << "sample_NativePointerRef_Char ChangeValue: " << *((char *)nativePoint->Value());
407 }
408 
HWTEST_F_L0(JSNApiSampleTest,sample_NativePointerRef_Long)409 HWTEST_F_L0(JSNApiSampleTest, sample_NativePointerRef_Long)
410 {
411     LocalScope scope(vm_);
412     void *vpl = new long(123456);
413     Local<NativePointerRef> nativePoint = NativePointerRef::New(vm_, vpl);
414     long *p = (long *)nativePoint->Value();
415     GTEST_LOG_(INFO) << "sample_NativePointerRef_Long Value : " << *p;
416     long value = 2147483647;
417     *p = value;
418     GTEST_LOG_(INFO) << "sample_NativePointerRef_Long ChangeValue: " << *((long *)nativePoint->Value());
419 }
420 
HWTEST_F_L0(JSNApiSampleTest,sample_NativePointerRef_Int)421 HWTEST_F_L0(JSNApiSampleTest, sample_NativePointerRef_Int)
422 {
423     LocalScope scope(vm_);
424     void *vpi = new int(123);
425     Local<NativePointerRef> nativePoint = NativePointerRef::New(vm_, vpi);
426     int *p = (int *)nativePoint->Value();
427     GTEST_LOG_(INFO) << "sample_NativePointerRef_Int Value : " << *p;
428     int value = 147483647;
429     *p = value;
430     GTEST_LOG_(INFO) << "sample_NativePointerRef_Int ChangeValue: " << *((int *)nativePoint->Value());
431 }
432 
433 /* demo3 对object的操作 */
GetSymbolRef(EcmaVM * vm)434 static std::vector<Local<SymbolRef>> GetSymbolRef(EcmaVM *vm)
435 {
436     GTEST_LOG_(INFO) << "GetSymbolRef";
437     static std::vector<Local<SymbolRef>> value = { SymbolRef::New(vm, StringRef::NewFromUtf8(vm, "symbolKey1")),
438                                                    SymbolRef::New(vm, StringRef::NewFromUtf8(vm, "symbolKey2")),
439                                                    SymbolRef::New(vm, StringRef::NewFromUtf8(vm, "symbolKey3")) };
440     return value;
441 }
442 
Setter1(JsiRuntimeCallInfo * info)443 Local<JSValueRef> Setter1(JsiRuntimeCallInfo *info)
444 {
445     GTEST_LOG_(INFO) << "Setter is running";
446     int cnt = 0; // 0 = first element
447     EscapeLocalScope scope(info->GetVM());
448     Local<JSValueRef> arg = info->GetCallArgRef(0);
449     Local<JSValueRef> value = info->GetThisRef();
450     Local<ObjectRef> obj = value->ToObject(info->GetVM());
451     if (value->IsNumber()) {
452         double num = value->ToNumber(info->GetVM())->Value();
453         int max = 100; // 100 = maxValue
454         int min = 0;   // 0 = minValue
455         if (num < min || num > max) {
456             return JSValueRef::Undefined(info->GetVM());
457         }
458     }
459     obj->Set(info->GetVM(), GetSymbolRef(info->GetVM())[cnt], arg);
460     return JSValueRef::Undefined(info->GetVM());
461 }
462 
Setter2(JsiRuntimeCallInfo * info)463 Local<JSValueRef> Setter2(JsiRuntimeCallInfo *info)
464 {
465     GTEST_LOG_(INFO) << "Setter is running";
466     int cnt = 1; // 1 = second element
467     EscapeLocalScope scope(info->GetVM());
468     Local<JSValueRef> arg = info->GetCallArgRef(0);
469     Local<JSValueRef> value = info->GetThisRef();
470     Local<ObjectRef> obj = value->ToObject(info->GetVM());
471     if (!arg->IsString(info->GetVM())) {
472         return JSValueRef::Undefined(info->GetVM());
473     }
474     obj->Set(info->GetVM(), GetSymbolRef(info->GetVM())[cnt], arg);
475     return JSValueRef::Undefined(info->GetVM());
476 }
477 
Setter3(JsiRuntimeCallInfo * info)478 Local<JSValueRef> Setter3(JsiRuntimeCallInfo *info)
479 {
480     GTEST_LOG_(INFO) << "Setter is running";
481     int cnt = 2; // 2 = third element
482     EscapeLocalScope scope(info->GetVM());
483     Local<JSValueRef> arg = info->GetCallArgRef(0);
484     Local<JSValueRef> value = info->GetThisRef();
485     Local<ObjectRef> obj = value->ToObject(info->GetVM());
486     if (!arg->IsSymbol(info->GetVM())) {
487         return JSValueRef::Undefined(info->GetVM());
488     }
489     obj->Set(info->GetVM(), GetSymbolRef(info->GetVM())[cnt], arg);
490     return JSValueRef::Undefined(info->GetVM());
491 }
492 
Getter1(JsiRuntimeCallInfo * info)493 Local<JSValueRef> Getter1(JsiRuntimeCallInfo *info)
494 {
495     GTEST_LOG_(INFO) << "Getter is running";
496     int cnt = 0; // 0 = first element
497     Local<JSValueRef> value = info->GetThisRef();
498     Local<ObjectRef> obj = value->ToObject(info->GetVM());
499     Local<JSValueRef> temp = obj->Get(info->GetVM(), GetSymbolRef(info->GetVM())[cnt]);
500     return temp->ToString(info->GetVM());
501 }
502 
Getter2(JsiRuntimeCallInfo * info)503 Local<JSValueRef> Getter2(JsiRuntimeCallInfo *info)
504 {
505     GTEST_LOG_(INFO) << "Getter is running";
506     int cnt = 1; // 1 = second element
507     Local<JSValueRef> value = info->GetThisRef();
508     Local<ObjectRef> obj = value->ToObject(info->GetVM());
509     Local<JSValueRef> temp = obj->Get(info->GetVM(), GetSymbolRef(info->GetVM())[cnt]);
510     return temp->ToString(info->GetVM());
511 }
512 
Getter3(JsiRuntimeCallInfo * info)513 Local<JSValueRef> Getter3(JsiRuntimeCallInfo *info)
514 {
515     GTEST_LOG_(INFO) << "Getter is running";
516     int cnt = 2; // 2 = third element
517     Local<JSValueRef> value = info->GetThisRef();
518     Local<ObjectRef> obj = value->ToObject(info->GetVM());
519     Local<JSValueRef> temp = obj->Get(info->GetVM(), GetSymbolRef(info->GetVM())[cnt]);
520     if (!temp->IsSymbol(info->GetVM())) {
521         JSValueRef::Undefined(info->GetVM());
522     }
523     Local<SymbolRef> str = temp;
524     return str->GetDescription(info->GetVM());
525 }
526 
ObjectRefSet(Local<ObjectRef> object,EcmaVM * vm,Local<SymbolRef> symbol)527 void ObjectRefSet(Local<ObjectRef> object, EcmaVM *vm, Local<SymbolRef> symbol)
528 {
529     GTEST_LOG_(INFO) << "ObjectRefSet";
530     int cnt = 1; // 1 = key
531     bool b = object->Set(vm, cnt, StringRef::NewFromUtf8(vm, "TestValue1"));
532     ASSERT_TRUE(b);
533     b = object->Set(vm, StringRef::NewFromUtf8(vm, "Test2"), StringRef::NewFromUtf8(vm, "TestValue2"));
534     ASSERT_TRUE(b);
535     b = object->Set(vm, StringRef::NewFromUtf8(vm, "Test3"), StringRef::NewFromUtf8(vm, "TestValue3"));
536     ASSERT_TRUE(b);
537     b = object->Set(vm, symbol, StringRef::NewFromUtf8(vm, "symbolValue"));
538     ASSERT_TRUE(b);
539 
540     Local<FunctionRef> getter1 = FunctionRef::New(vm, Getter1);
541     Local<FunctionRef> setter1 = FunctionRef::New(vm, Setter1);
542 
543     Local<FunctionRef> getter2 = FunctionRef::New(vm, Getter2);
544     Local<FunctionRef> setter2 = FunctionRef::New(vm, Setter2);
545 
546     Local<FunctionRef> getter3 = FunctionRef::New(vm, Getter3);
547     Local<FunctionRef> setter3 = FunctionRef::New(vm, Setter3);
548 
549     PropertyAttribute attribute1(StringRef::NewFromUtf8(vm, "AttributeValue1"), true, true, false);
550     PropertyAttribute attribute2(StringRef::NewFromUtf8(vm, "AttributeValue2"), false, true, true);
551     PropertyAttribute attribute3(StringRef::NewFromUtf8(vm, "AttributeValue3"), true, false, true);
552     attribute1.SetGetter(getter1);
553     attribute1.SetSetter(setter1);
554     b = object->DefineProperty(vm, StringRef::NewFromUtf8(vm, "AttributeKey1"), attribute1);
555     ASSERT_TRUE(b);
556     b = object->DefineProperty(vm, StringRef::NewFromUtf8(vm, "Test2"), attribute2);
557     ASSERT_TRUE(b);
558     b = object->SetAccessorProperty(vm, StringRef::NewFromUtf8(vm, "Accessor1"), getter1, setter1);
559     ASSERT_TRUE(b);
560     b = object->SetAccessorProperty(vm, StringRef::NewFromUtf8(vm, "Test3"), getter2, setter2);
561     ASSERT_TRUE(b);
562     b = object->DefineProperty(vm, StringRef::NewFromUtf8(vm, "AttributeKey3"), attribute3);
563     ASSERT_TRUE(b);
564     b = object->SetAccessorProperty(vm, StringRef::NewFromUtf8(vm, "AttributeKey3"), getter3, setter3, attribute3);
565     ASSERT_TRUE(b);
566 }
567 
GetProperty(Local<ObjectRef> object,EcmaVM * vm)568 void GetProperty(Local<ObjectRef> object, EcmaVM *vm)
569 {
570     GTEST_LOG_(INFO) << "GetProperty";
571     Local<ArrayRef> names = object->GetOwnPropertyNames(vm);
572     int cnt = names->Length(vm);
573     GTEST_LOG_(INFO) << "GetOwnPropertyNames cnt: " << cnt;
574     for (int i = 0; i < cnt; i++) {
575         Local<JSValueRef> value = ArrayRef::GetValueAt(vm, names, i);
576         if (value->IsSymbol(vm)) {
577             Local<SymbolRef> symbol = value;
578             GTEST_LOG_(INFO) << "PropertyNames: " << symbol->GetDescription(vm)->ToString(vm);
579         } else {
580             GTEST_LOG_(INFO) << "PropertyNames: " << value->ToString(vm)->ToString(vm);
581         }
582     }
583 }
584 
Get(Local<ObjectRef> object,EcmaVM * vm)585 void Get(Local<ObjectRef> object, EcmaVM *vm)
586 {
587     GTEST_LOG_(INFO) << "Get";
588     int cnt = 1; // 1 = key
589     Local<JSValueRef> value = object->Get(vm, cnt);
590     if (value->IsString(vm)) {
591         GTEST_LOG_(INFO) << "Key:1  Value:" << value->ToString(vm)->ToString(vm);
592     }
593     value = object->Get(vm, StringRef::NewFromUtf8(vm, "Test2"));
594     if (value->IsString(vm)) {
595         GTEST_LOG_(INFO) << "Key:Test2  Value:" << value->ToString(vm)->ToString(vm);
596     }
597     value = object->Get(vm, StringRef::NewFromUtf8(vm, "AttributeKey1"));
598     if (value->IsString(vm)) {
599         GTEST_LOG_(INFO) << "Key:AttributeKey1  Value:" << value->ToString(vm)->ToString(vm);
600     }
601     int num = 10; // 10 = randomness
602     object->Set(vm, StringRef::NewFromUtf8(vm, "Accessor1"), NumberRef::New(vm, num));
603     object->Set(vm, StringRef::NewFromUtf8(vm, "Test3"), StringRef::NewFromUtf8(vm, "Test3Value"));
604     object->Set(vm, StringRef::NewFromUtf8(vm, "AttributeKey3"),
605         SymbolRef::New(vm, StringRef::NewFromUtf8(vm, "AttributeKey3Value")));
606     Local<StringRef> str = object->Get(vm, StringRef::NewFromUtf8(vm, "AttributeKey3"));
607     if (str->IsString(vm)) {
608         GTEST_LOG_(INFO) << "Key:AttributeKey3  Value:" << str->ToString(vm);
609     }
610     str = object->Get(vm, StringRef::NewFromUtf8(vm, "Accessor1"));
611     if (str->IsString(vm)) {
612         GTEST_LOG_(INFO) << "Key:Accessor1  Value:" << str->ToString(vm);
613     }
614     str = object->Get(vm, StringRef::NewFromUtf8(vm, "Test3"));
615     if (str->IsString(vm)) {
616         GTEST_LOG_(INFO) << "Key:Test3  Value:" << str->ToString(vm);
617     }
618 }
619 
SetValueAgain(Local<ObjectRef> object,EcmaVM * vm)620 void SetValueAgain(Local<ObjectRef> object, EcmaVM *vm)
621 {
622     GTEST_LOG_(INFO) << "SetValueAgain";
623     GTEST_LOG_(INFO) << "SetValueAgain";
624     int cnt = 1; // 1 = key
625     bool b = object->Set(vm, cnt, StringRef::NewFromUtf8(vm, "TestValueAgain1"));
626     ASSERT_TRUE(b);
627     b = object->Set(vm, StringRef::NewFromUtf8(vm, "Test3"), StringRef::NewFromUtf8(vm, "TestValueAgain3"));
628     ASSERT_TRUE(b);
629     b = object->Set(vm, StringRef::NewFromUtf8(vm, "AttributeKey1"),
630         StringRef::NewFromUtf8(vm, "AttributeValueAgain1"));
631     ASSERT_TRUE(b);
632     b = object->Set(vm, StringRef::NewFromUtf8(vm, "AttributeKey3"),
633         StringRef::NewFromUtf8(vm, "AttributeValueAgain3"));
634     ASSERT_TRUE(b);
635     b = object->Set(vm, StringRef::NewFromUtf8(vm, "Accessor1"), StringRef::NewFromUtf8(vm, "AttributeValueAgain2"));
636     ASSERT_TRUE(b);
637     GTEST_LOG_(INFO) << "GetValueAgain";
638     Get(object, vm);
639     GetProperty(object, vm);
640 }
641 
GetOwnEnumerablePropertyNames(Local<ObjectRef> object,EcmaVM * vm)642 void GetOwnEnumerablePropertyNames(Local<ObjectRef> object, EcmaVM *vm)
643 {
644     GTEST_LOG_(INFO) << "GetOwnEnumerablePropertyNames";
645     Local<ArrayRef> names = object->GetOwnEnumerablePropertyNames(vm);
646     int cnt = names->Length(vm);
647     GTEST_LOG_(INFO) << "GetOwnEnumerablePropertyNames cnt: " << cnt;
648     for (int i = 0; i < cnt; i++) {
649         Local<JSValueRef> value = ArrayRef::GetValueAt(vm, names, i);
650         if (value->IsSymbol(vm)) {
651             Local<SymbolRef> symbol = value;
652             GTEST_LOG_(INFO) << "PropertyNames: " << symbol->GetDescription(vm)->ToString(vm);
653         } else {
654             GTEST_LOG_(INFO) << "PropertyNames: " << value->ToString(vm)->ToString(vm);
655         }
656     }
657 }
658 
PrintAllProperty(Local<ObjectRef> object,EcmaVM * vm,int flag)659 void PrintAllProperty(Local<ObjectRef> object, EcmaVM *vm, int flag)
660 {
661     Local<ArrayRef> names = object->GetAllPropertyNames(vm, flag);
662     int cnt = names->Length(vm);
663     switch (flag) {
664         case 0: // 0 = NATIVE_DEFAULT
665             GTEST_LOG_(INFO) << "GetOwnPropertyNames NATIVE_DEFAULT: " << cnt;
666             break;
667         case 1: // 1 = NATIVE_WRITABLE
668             GTEST_LOG_(INFO) << "GetOwnPropertyNames NATIVE_WRITABLE: " << cnt;
669             break;
670         case 2: // 2 = NATIVE_ENUMERABLE
671             GTEST_LOG_(INFO) << "GetOwnPropertyNames NATIVE_ENUMERABLE: " << cnt;
672             break;
673         case 3: // 3 = NATIVE_CONFIGURABLE
674             GTEST_LOG_(INFO) << "GetOwnPropertyNames NATIVE_CONFIGURABLE: " << cnt;
675             break;
676         default:
677             break;
678     }
679     for (int i = 0; i < cnt; i++) {
680         Local<JSValueRef> value = ArrayRef::GetValueAt(vm, names, i);
681         if (value->IsSymbol(vm)) {
682             Local<SymbolRef> symbol = value;
683             GTEST_LOG_(INFO) << "PropertyNames: " << symbol->GetDescription(vm)->ToString(vm);
684         } else {
685             GTEST_LOG_(INFO) << "PropertyNames: " << value->ToString(vm)->ToString(vm);
686         }
687     }
688 }
689 
GetAllPropertyNames(Local<ObjectRef> object,EcmaVM * vm)690 void GetAllPropertyNames(Local<ObjectRef> object, EcmaVM *vm)
691 {
692     GTEST_LOG_(INFO) << "GetAllPropertyNames";
693     for (int i = 0; i < 4; i++) { // 4 show Go through all the properties
694         PrintAllProperty(object, vm, i);
695     }
696 }
697 
HasAndDelete(Local<ObjectRef> object,EcmaVM * vm)698 void HasAndDelete(Local<ObjectRef> object, EcmaVM *vm)
699 {
700     GTEST_LOG_(INFO) << "HasAndDelete";
701     bool b = object->Has(vm, 1); // 1 = key
702     ASSERT_TRUE(b);
703     b = object->Has(vm, StringRef::NewFromUtf8(vm, "Test2"));
704     ASSERT_TRUE(b);
705     b = object->Delete(vm, StringRef::NewFromUtf8(vm, "Test2"));
706     ASSERT_TRUE(b);
707     b = object->Has(vm, StringRef::NewFromUtf8(vm, "Test2"));
708     ASSERT_FALSE(b);
709 }
710 
FreezeAndSeal(Local<ObjectRef> object,EcmaVM * vm)711 void FreezeAndSeal(Local<ObjectRef> object, EcmaVM *vm)
712 {
713     GTEST_LOG_(INFO) << "FreezeAndSeal";
714     object->Seal(vm);
715     int num1 = 1; // 1 = key
716     int num2 = 2; // 2 = key
717     bool b = object->Set(vm, num1, StringRef::NewFromUtf8(vm, "Seal1"));
718     ASSERT_TRUE(b);
719     b = object->Delete(vm, num1);
720     ASSERT_FALSE(b);
721     b = object->Set(vm, num2, StringRef::NewFromUtf8(vm, "2"));
722     ASSERT_FALSE(b);
723     object->Freeze(vm);
724     PropertyAttribute attribute(StringRef::NewFromUtf8(vm, "FreezeValue"), true, true, false);
725     b = object->DefineProperty(vm, StringRef::NewFromUtf8(vm, "Freeze"), attribute);
726     ASSERT_FALSE(b);
727     b = object->Has(vm, num2);
728     ASSERT_FALSE(b);
729     b = object->Has(vm, StringRef::NewFromUtf8(vm, "Freeze"));
730     ASSERT_FALSE(b);
731     b = object->Delete(vm, num2);
732     ASSERT_FALSE(b);
733     b = object->Delete(vm, StringRef::NewFromUtf8(vm, "Freeze"));
734     ASSERT_FALSE(b);
735 }
736 
GetOwnProperty(Local<ObjectRef> object,EcmaVM * vm)737 void GetOwnProperty(Local<ObjectRef> object, EcmaVM *vm)
738 {
739     GTEST_LOG_(INFO) << "GetOwnProperty";
740     PropertyAttribute value1;
741     bool b = object->GetOwnProperty(vm, NumberRef::New(vm, 1), value1);
742     ASSERT_TRUE(b);
743     PropertyAttribute value2;
744     b = object->GetOwnProperty(vm, StringRef::NewFromUtf8(vm, "AttributeKey1"), value2);
745     ASSERT_TRUE(b);
746     ASSERT_EQ(true, value2.IsWritable());
747     ASSERT_EQ(true, value2.IsEnumerable());
748     ASSERT_EQ(false, value2.IsConfigurable());
749     ASSERT_EQ(true, value2.HasWritable());
750     ASSERT_EQ(true, value2.HasConfigurable());
751     ASSERT_EQ(true, value2.HasEnumerable());
752     Local<JSValueRef> value = value2.GetValue(vm);
753     ASSERT_EQ("AttributeValue1", value->ToString(vm)->ToString(vm));
754 }
755 
756 class A {
757 public:
Test() const758     void Test() const
759     {
760         GTEST_LOG_(INFO) << "Class A Test()";
761     }
762 };
763 
NativePointer(Local<ObjectRef> object,EcmaVM * vm)764 void NativePointer(Local<ObjectRef> object, EcmaVM *vm)
765 {
766     GTEST_LOG_(INFO) << "NativePointer";
767     int cnt = 10; // 10 = accommodate quantity
768     object->SetNativePointerFieldCount(vm, cnt);
769     ASSERT_EQ(cnt, object->GetNativePointerFieldCount(vm));
770     A *a = new A();
771     int cnt2 = 1;  // 11 = random Numbers
772     int cnt3 = 11; // 1 = random Numbers
773     object->SetNativePointerField(vm, cnt2, static_cast<void *>(a), nullptr, nullptr);
774     object->SetNativePointerField(vm, cnt3, static_cast<void *>(a), nullptr, nullptr);
775     A *value1 = static_cast<A *>(object->GetNativePointerField(vm, cnt2));
776     A *value2 = static_cast<A *>(object->GetNativePointerField(vm, cnt3));
777     if (value1 == nullptr) {
778         GTEST_LOG_(INFO) << "SetNativePointerField is Error";
779     } else {
780         value1->Test();
781     }
782     if (value2 == nullptr) {
783         GTEST_LOG_(INFO) << "SetNativePointerField is OK";
784     }
785     Local<NativePointerRef> native = NativePointerRef::New(vm, static_cast<void *>(a));
786     bool b = object->ConvertToNativeBindingObject(vm, native);
787     ASSERT_TRUE(b);
788 }
789 
SetPrototype(Local<ObjectRef> object,EcmaVM * vm)790 void SetPrototype(Local<ObjectRef> object, EcmaVM *vm)
791 {
792     GTEST_LOG_(INFO) << "SetPrototype";
793     int cnt = 111; // 111 = random Numbers
794     Local<NumberRef> obj = NumberRef::New(vm, cnt);
795     object->SetPrototype(vm, obj);
796     Local<JSValueRef> type = object->GetPrototype(vm);
797     if (type->IsUndefined() || type->IsNull()) {
798         return;
799     }
800     GTEST_LOG_(INFO) << "Prototype: " << type->Typeof(vm)->ToString(vm);
801 }
802 
HWTEST_F_L0(JSNApiSampleTest,Sample_Demo3_ObjectRef)803 HWTEST_F_L0(JSNApiSampleTest, Sample_Demo3_ObjectRef)
804 {
805     GTEST_LOG_(INFO) << "SetPrototype";
806     LocalScope scope(vm_);
807     GetSymbolRef(vm_);
808     Local<SymbolRef> symbol = SymbolRef::New(vm_, StringRef::NewFromUtf8(vm_, "Symbol"));
809     Local<ObjectRef> object = ObjectRef::New(vm_);
810     SetPrototype(object, vm_);
811     ObjectRefSet(object, vm_, symbol);
812     GetProperty(object, vm_);
813     GetOwnProperty(object, vm_);
814     GetAllPropertyNames(object, vm_);
815     GetOwnEnumerablePropertyNames(object, vm_);
816     Get(object, vm_);
817     NativePointer(object, vm_);
818     SetValueAgain(object, vm_);
819     HasAndDelete(object, vm_);
820     FreezeAndSeal(object, vm_);
821 }
822 
823 /* demo4 无参无返回值的函数的调用。 ts:
824  * function FuncTest(): void {
825  * console.log("func test log ...");
826  * }
827  * FuncTest();
828  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo4_function_test_1)829 HWTEST_F_L0(JSNApiSampleTest, sample_demo4_function_test_1)
830 {
831     GTEST_LOG_(INFO) << "sample_demo4_function_test_1 =======================================";
832     LocalScope scope(vm_);
833 
834     Local<FunctionRef> FuncTest = FunctionRef::New(vm_, [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
835         EcmaVM *vm = runtimeInfo->GetVM();
836         LocalScope scope(vm);
837         GTEST_LOG_(INFO) << "func test log ...";
838         return JSValueRef::Undefined(vm);
839     });
840     FuncTest->Call(vm_, JSValueRef::Undefined(vm_), nullptr, 0);
841     GTEST_LOG_(INFO) << "sample_demo4_function_test_1 ==========================================";
842 }
843 
844 /* demo4 有参有返回值的函数的调用。 ts:
845  * function Add(x: number, y: number): number {
846  * return x + y;
847  * }
848  * let sum = Add(12, 34);
849  * console.log(sum);
850  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo4_function_test_2)851 HWTEST_F_L0(JSNApiSampleTest, sample_demo4_function_test_2)
852 {
853     GTEST_LOG_(INFO) << "sample_demo4_function_test_2 =======================================";
854     LocalScope scope(vm_);
855     Local<FunctionRef> Add = FunctionRef::New(vm_, [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
856         EcmaVM *vm = runtimeInfo->GetVM();
857         LocalScope scope(vm);
858         // 参数的个数。
859         uint32_t argsCount = runtimeInfo->GetArgsNumber();
860         // 遍历参数。
861         for (uint32_t i = 0; i < argsCount; ++i) {
862             Local<JSValueRef> arg = runtimeInfo->GetCallArgRef(i);
863             GTEST_LOG_(INFO) << "func test arg " << i << "   " << arg->Int32Value(vm);
864         }
865         // 获取前两个参数。
866         Local<JSValueRef> jsArg0 = runtimeInfo->GetCallArgRef(0);
867         Local<JSValueRef> jsArg1 = runtimeInfo->GetCallArgRef(1);
868         int arg0 = jsArg0->Int32Value(vm);
869         int arg1 = jsArg1->Int32Value(vm);
870         int sum = arg0 + arg1;
871         GTEST_LOG_(INFO) << "func test sum " << sum;
872         // 参数返回值
873         return NumberRef::New(vm, sum);
874     });
875     int argv0 = 12; // random number
876     int argv1 = 34; // random number
877     Local<JSValueRef> *argv = new Local<JSValueRef>[2];
878     argv[0] = NumberRef::New(vm_, argv0);
879     argv[1] = NumberRef::New(vm_, argv1);
880     Local<JSValueRef> jsSum = Add->Call(vm_, JSValueRef::Undefined(vm_), argv, 2);
881     int sum = jsSum->Int32Value(vm_);
882     GTEST_LOG_(INFO) << "func test call sum " << sum;
883     GTEST_LOG_(INFO) << "sample_demo4_function_test_2 ==========================================";
884 }
885 
AddFunc(JsiRuntimeCallInfo * runtimeInfo)886 Local<JSValueRef> AddFunc(JsiRuntimeCallInfo *runtimeInfo)
887 {
888     EcmaVM *vm = runtimeInfo->GetVM();
889     LocalScope scope(vm);
890     // 参数的个数。
891     uint32_t argsCount = runtimeInfo->GetArgsNumber();
892     // 遍历参数。
893     for (uint32_t i = 0; i < argsCount; ++i) {
894         Local<JSValueRef> arg = runtimeInfo->GetCallArgRef(i);
895         GTEST_LOG_(INFO) << "func test arg " << i << "   " << arg->Int32Value(vm);
896     }
897     // 获取前两个参数。
898     Local<JSValueRef> jsArg0 = runtimeInfo->GetCallArgRef(0);
899     Local<JSValueRef> jsArg1 = runtimeInfo->GetCallArgRef(1);
900     int arg0 = jsArg0->Int32Value(vm);
901     int arg1 = jsArg1->Int32Value(vm);
902     int sum = arg0 + arg1;
903     // 参数返回值
904     return NumberRef::New(vm, sum);
905 }
906 
AddProxyFunc(JsiRuntimeCallInfo * runtimeInfo)907 Local<JSValueRef> AddProxyFunc(JsiRuntimeCallInfo *runtimeInfo)
908 {
909     EcmaVM *vm = runtimeInfo->GetVM();
910     LocalScope scope(vm);
911     // 参数的个数。
912     uint32_t argsCount = runtimeInfo->GetArgsNumber();
913     // 函数调用的时候的传参个数,如果不能等于这个值说明函数调用有问题。
914     uint32_t defaultArgsCount = 3;
915     if (argsCount != defaultArgsCount) {
916         return NumberRef::New(vm, 0);
917     }
918     // 函数
919     int index = 0; // 获取参数的索引。
920     Local<JSValueRef> jsArg0 = runtimeInfo->GetCallArgRef(index);
921     // 获取前两个参数。
922     index++;
923     Local<JSValueRef> jsArg1 = runtimeInfo->GetCallArgRef(index);
924     index++;
925     Local<JSValueRef> jsArg2 = runtimeInfo->GetCallArgRef(index);
926     Local<FunctionRef> addFunc = jsArg0;
927     const int addFuncArgCount = 2; // 内部调用的函数的参数个数。
928     Local<JSValueRef> argv[addFuncArgCount] = { jsArg1, jsArg2 };
929     Local<JSValueRef> jsSum = addFunc->Call(vm, JSValueRef::Undefined(vm), argv, addFuncArgCount);
930     int sum = jsSum->Int32Value(vm);
931     int multiple = 2; // 代理的功能,原函数的2倍返回。
932     sum *= multiple;
933     // 参数返回值
934     return NumberRef::New(vm, sum);
935 }
936 
937 /* demo4 参数是函数的调用。 ts:
938  * function Add(x: number, y: number): number {
939  * return x + y;
940  * }
941  * function AddProxy(add: (x: number, y: number) => number, x: number, y: number) {
942  * let sum = add(x, y);
943  * return sum * 2
944  * }
945  * let sum1 = Add(12, 34);
946  * let sum2 = AddProxy(Add,12, 34);
947  * console.log(sum1);
948  * console.log(sum2);
949  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo4_function_test_3)950 HWTEST_F_L0(JSNApiSampleTest, sample_demo4_function_test_3)
951 {
952     GTEST_LOG_(INFO) << "sample_demo4_function_test_3 =======================================";
953     LocalScope scope(vm_);
954     Local<FunctionRef> Add = FunctionRef::New(vm_, AddFunc);
955     Local<FunctionRef> AddProxy = FunctionRef::New(vm_, AddProxyFunc);
956     int num1 = 12; // random number
957     int num2 = 34; // random number
958     Local<JSValueRef> addArgv[2];
959     addArgv[0] = NumberRef::New(vm_, num1);
960     addArgv[1] = NumberRef::New(vm_, num2);
961     Local<JSValueRef> addProxyArgv[3];
962     addProxyArgv[0] = Add;
963     addProxyArgv[1] = NumberRef::New(vm_, num1);
964     addProxyArgv[2] = NumberRef::New(vm_, num2);
965     Local<JSValueRef> jsSum1 = Add->Call(vm_, JSValueRef::Undefined(vm_), addArgv, 2);
966     Local<JSValueRef> jsSum2 = AddProxy->Call(vm_, JSValueRef::Undefined(vm_), addProxyArgv, 3);
967     int sum1 = jsSum1->Int32Value(vm_);
968     int sum2 = jsSum2->Int32Value(vm_);
969     GTEST_LOG_(INFO) << "func test call Add , sum = " << sum1;
970     GTEST_LOG_(INFO) << "func test call AddProxy , sum = " << sum2;
971     GTEST_LOG_(INFO) << "sample_demo4_function_test_3 ==========================================";
972 }
973 
974 /* demo5 类的静态函数和非静态函数的测试,静态变量变量 和 非静态变量的测试。 ts:
975  * class Greeter {
976  * // 静态变量。
977  * static position:string = "door";
978  * // 私有静态变量。
979  * private static standardGreetingStr:string = "Hello, there";
980  *
981  * // 私有非静态变量。
982  * private privateGreeting: string;
983  * // 非静态变量。
984  * greeting: string;
985  *
986  * // 构造函数。
987  * constructor(greet: string) {
988  * this.greeting = greet;
989  * }
990  *
991  * // 非静态函数。
992  * SetPrivateGreeting(priGreeting: string):void
993  * {
994  * this.privateGreeting = priGreeting;
995  * }
996  *
997  * // 非静态函数调用。
998  * Greet(): string {
999  * if (this.privateGreeting) {
1000  * return "Hello, " + this.privateGreeting;
1001  * }else if (this.greeting) {
1002  * return "Hello, " + this.greeting;
1003  * }
1004  * else {
1005  * return Greeter.standardGreetingStr;
1006  * }
1007  * }
1008  *
1009  * // 静态函数调用。
1010  * static StandardGreeting(): string {
1011  * return Greeter.standardGreetingStr;
1012  * }
1013  *
1014  * // 静态函数调用。
1015  * static StandardPosition(): string {
1016  * return Greeter.position;
1017  * }
1018  *
1019  * }
1020  *
1021  * let greeter1: Greeter = new Greeter("everyone");
1022  *
1023  * // 非静态函数调用
1024  * console.log(greeter1.Greet());
1025  *
1026  * greeter1.SetPrivateGreeting("vip");
1027  * console.log(greeter1.Greet());
1028  *
1029  * greeter1.SetPrivateGreeting("");
1030  * console.log(greeter1.Greet());
1031  *
1032  * // 修改变量
1033  * greeter1.greeting = "";
1034  * console.log(greeter1.Greet());
1035  *
1036  * // 静态函数调用。
1037  * console.log(Greeter.StandardGreeting());
1038  * console.log(Greeter.StandardPosition());
1039  *
1040  * // 修改静态变量。
1041  * Greeter.position = "house";
1042  * console.log(Greeter.StandardPosition());
1043  */
1044 class Tag {
1045 public:
Tag(const std::string name)1046     explicit Tag(const std::string name) : name_(name)
1047     {
1048         GTEST_LOG_(INFO) << "tag construction , name is " << name_;
1049     }
~Tag()1050     ~Tag()
1051     {
1052         GTEST_LOG_(INFO) << "tag deconstruction , name is " << name_;
1053     }
1054 
1055 private:
1056     std::string name_;
1057 };
1058 
1059 class Greeter {
1060 private:
1061     // 新建ClassFunction
1062     static Local<FunctionRef> NewClassFunction(EcmaVM *vm);
1063 
1064     // 添加静态变量。
1065     static void AddStaticVariable(EcmaVM *vm, Local<FunctionRef> &claFunc);
1066     // 添加静态函数。
1067     static void AddStaticFunction(EcmaVM *vm, Local<FunctionRef> &claFunc);
1068 
1069     // 添加非静态变量。
1070     static void AddVariable(EcmaVM *vm, Local<ObjectRef> &proto);
1071     // 添加非静态函数。
1072     static void AddFunction(EcmaVM *vm, Local<ObjectRef> &proto);
1073 
1074 public:
1075     // 获取ClassFunction
1076     static Local<FunctionRef> GetClassFunction(EcmaVM *vm);
1077     static Local<Greeter> New(EcmaVM *vm, Local<StringRef> greet);
1078 
1079     // 非静态函数调用。
1080     static void SetPrivateGreeting(EcmaVM *vm, Local<Greeter> thisRef, Local<StringRef> priGreeting);
1081     static Local<StringRef> Greet(EcmaVM *vm, Local<Greeter> thisRef);
1082 
1083     // 静态函数的调用。
1084     static Local<StringRef> StandardGreeting(EcmaVM *vm);
1085     static Local<StringRef> StandardPosition(EcmaVM *vm);
1086 
1087 private:
1088     static Local<SymbolRef> standardGreetingStrKey;
1089     static Local<SymbolRef> privateGreetingKey;
1090 
1091     // 类名
1092     const static std::string CLASS_NAME;
1093 };
1094 
1095 Local<SymbolRef> Greeter::standardGreetingStrKey;
1096 Local<SymbolRef> Greeter::privateGreetingKey;
1097 
1098 const std::string Greeter::CLASS_NAME = "GreeterClass";
1099 
NewClassFunction(EcmaVM * vm)1100 Local<FunctionRef> Greeter::NewClassFunction(EcmaVM *vm)
1101 {
1102     // 初始化私有静态变量的key。
1103     Greeter::standardGreetingStrKey = SymbolRef::New(vm, StringRef::NewFromUtf8(vm, "standardGreetingStr"));
1104     Greeter::privateGreetingKey = SymbolRef::New(vm, StringRef::NewFromUtf8(vm, "privateGreeting"));
1105 
1106     Tag *tag = new Tag("ClassFunctionTag");
1107     Local<FunctionRef> claFunc = FunctionRef::NewClassFunction(
1108         vm,
1109         // 构造函数调用
1110         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
1111             EcmaVM *vm = runtimeInfo->GetVM();
1112             LocalScope scope(vm);
1113             // 获取this
1114             Local<JSValueRef> jsThisRef = runtimeInfo->GetThisRef();
1115             Local<ObjectRef> thisRef = jsThisRef->ToObject(vm);
1116             // 获取参数。
1117             Local<JSValueRef> greet = runtimeInfo->GetCallArgRef(0);
1118             // ts: this.greeting = greet;
1119             thisRef->Set(vm, StringRef::NewFromUtf8(vm, "greeting"), greet);
1120             return thisRef;
1121         },
1122         [](void *env, void *nativePointer, void *data) {
1123             GTEST_LOG_(INFO) << "NewClassFunction, nativePointer is " << nativePointer;
1124             Tag *t = static_cast<Tag *>(data);
1125             delete t;
1126         },
1127         tag);
1128     // static 添加 到  claFunc。
1129     // 添加静态变量。
1130     AddStaticVariable(vm, claFunc);
1131     // 添加静态函数
1132     AddStaticFunction(vm, claFunc);
1133     Local<JSValueRef> jsProto = claFunc->GetFunctionPrototype(vm);
1134     Local<ObjectRef> proto = jsProto->ToObject(vm);
1135     // 非static 添加到 proto。
1136     // 添加非静态变量
1137     AddVariable(vm, proto);
1138     // 添加非静态函数
1139     AddFunction(vm, proto);
1140     // 设置类名。
1141     claFunc->SetName(vm, StringRef::NewFromUtf8(vm, Greeter::CLASS_NAME.c_str()));
1142     return claFunc;
1143 }
1144 
GetClassFunction(EcmaVM * vm)1145 Local<FunctionRef> Greeter::GetClassFunction(EcmaVM *vm)
1146 {
1147     Local<ObjectRef> globalObj = JSNApi::GetGlobalObject(vm);
1148     Local<JSValueRef> jsClaFunc = globalObj->Get(vm, StringRef::NewFromUtf8(vm, Greeter::CLASS_NAME.c_str()));
1149     if (jsClaFunc->IsFunction(vm)) {
1150         return jsClaFunc;
1151     }
1152     Local<FunctionRef> claFunc = Greeter::NewClassFunction(vm);
1153     // 添加到全局。
1154     globalObj->Set(vm, claFunc->GetName(vm), claFunc);
1155     return claFunc;
1156 }
1157 
1158 // 添加静态变量。
AddStaticVariable(EcmaVM * vm,Local<FunctionRef> & claFunc)1159 void Greeter::AddStaticVariable(EcmaVM *vm, Local<FunctionRef> &claFunc)
1160 {
1161     // 静态变量。
1162     // static position:string = "door";
1163     claFunc->Set(vm, StringRef::NewFromUtf8(vm, "position"), StringRef::NewFromUtf8(vm, "door"));
1164     // 私有静态变量。
1165     // private static standardGreetingStr:string = "Hello, there";
1166     claFunc->Set(vm, Greeter::standardGreetingStrKey, StringRef::NewFromUtf8(vm, "Hello, there"));
1167 }
1168 
1169 // 添加静态函数。
AddStaticFunction(EcmaVM * vm,Local<FunctionRef> & claFunc)1170 void Greeter::AddStaticFunction(EcmaVM *vm, Local<FunctionRef> &claFunc)
1171 {
1172     // 静态函数调用。
1173     claFunc->Set(vm, StringRef::NewFromUtf8(vm, "StandardGreeting"),
1174         FunctionRef::New(vm,
1175         // 函数体
1176         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
1177             EcmaVM *vm = runtimeInfo->GetVM();
1178             LocalScope scope(vm);
1179             Local<FunctionRef> claFunc = Greeter::GetClassFunction(vm);
1180             Local<JSValueRef> jsStandardGreetingStr = claFunc->Get(vm, Greeter::standardGreetingStrKey);
1181             return jsStandardGreetingStr;
1182         }));
1183     // 静态函数调用。
1184     claFunc->Set(vm, StringRef::NewFromUtf8(vm, "StandardPosition"),
1185         FunctionRef::New(vm,
1186         // 函数体
1187         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
1188             EcmaVM *vm = runtimeInfo->GetVM();
1189             LocalScope scope(vm);
1190             Local<FunctionRef> claFunc = Greeter::GetClassFunction(vm);
1191             Local<JSValueRef> jsPosition = claFunc->Get(vm, StringRef::NewFromUtf8(vm, "position"));
1192             return jsPosition;
1193         }));
1194 }
1195 
1196 // 添加非静态变量。
AddVariable(EcmaVM * vm,Local<ObjectRef> & proto)1197 void Greeter::AddVariable(EcmaVM *vm, Local<ObjectRef> &proto)
1198 {
1199     // 私有非静态变量。
1200     proto->Set(vm, Greeter::privateGreetingKey, JSValueRef::Undefined(vm));
1201     // 非静态变量。
1202     proto->Set(vm, StringRef::NewFromUtf8(vm, "greeting"), JSValueRef::Undefined(vm));
1203 }
1204 
1205 // 添加非静态函数。
AddFunction(EcmaVM * vm,Local<ObjectRef> & proto)1206 void Greeter::AddFunction(EcmaVM *vm, Local<ObjectRef> &proto)
1207 {
1208     // 非静态函数。
1209     proto->Set(vm, StringRef::NewFromUtf8(vm, "SetPrivateGreeting"),
1210         FunctionRef::New(vm,
1211         // 函数体
1212         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
1213             EcmaVM *vm = runtimeInfo->GetVM();
1214             LocalScope scope(vm);
1215             // 获取this
1216             Local<JSValueRef> jsThisRef = runtimeInfo->GetThisRef();
1217             Local<ObjectRef> thisRef = jsThisRef->ToObject(vm);
1218             // 获取参数。
1219             Local<JSValueRef> priGreeting = runtimeInfo->GetCallArgRef(0);
1220             thisRef->Set(vm, Greeter::privateGreetingKey, priGreeting);
1221             return JSValueRef::Undefined(vm);
1222         }));
1223     // 非静态函数。
1224     proto->Set(vm, StringRef::NewFromUtf8(vm, "Greet"),
1225         FunctionRef::New(vm,
1226         // 函数体
1227         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
1228             EcmaVM *vm = runtimeInfo->GetVM();
1229             LocalScope scope(vm);
1230             // 获取类
1231             Local<FunctionRef> claFunc = Greeter::GetClassFunction(vm);
1232             // 获取this
1233             Local<JSValueRef> jsThisRef = runtimeInfo->GetThisRef();
1234             Local<ObjectRef> thisRef = jsThisRef->ToObject(vm);
1235             Local<JSValueRef> jsPrivateGreeting = thisRef->Get(vm, Greeter::privateGreetingKey);
1236             Local<JSValueRef> jsGreeting = thisRef->Get(vm, StringRef::NewFromUtf8(vm, "greeting"));
1237             Local<JSValueRef> jsStandardGreetingStr = claFunc->Get(vm, Greeter::standardGreetingStrKey);
1238             std::string ret;
1239             if (jsPrivateGreeting->IsString(vm)) {
1240                 ret.append("Hello, ").append(jsPrivateGreeting->ToString(vm)->ToString(vm));
1241             } else if (jsGreeting->IsString(vm)) {
1242                 ret.append("Hello, ").append(jsGreeting->ToString(vm)->ToString(vm));
1243             } else {
1244                 ret.append(jsStandardGreetingStr->ToString(vm)->ToString(vm));
1245             }
1246             return StringRef::NewFromUtf8(vm, ret.c_str(), ret.size());
1247         }));
1248 }
1249 
New(EcmaVM * vm,Local<StringRef> greet)1250 Local<Greeter> Greeter::New(EcmaVM *vm, Local<StringRef> greet)
1251 {
1252     // 获取类函数。
1253     Local<FunctionRef> claFunc = Greeter::GetClassFunction(vm);
1254     // 定义参数。
1255     Local<JSValueRef> argv[1] = {greet};
1256     // 构造函数,构造对象。
1257     Local<JSValueRef> jsObj = claFunc->Constructor(vm, argv, 1);
1258     Local<ObjectRef> obj = jsObj->ToObject(vm);
1259     return obj;
1260 }
1261 
1262 /* // 非静态函数调用。 ts:
1263  * SetPrivateGreeting(priGreeting: string):void
1264  */
SetPrivateGreeting(EcmaVM * vm,Local<Greeter> thisRef,Local<StringRef> priGreeting)1265 void Greeter::SetPrivateGreeting(EcmaVM *vm, Local<Greeter> thisRef, Local<StringRef> priGreeting)
1266 {
1267     Local<ObjectRef> objRef = thisRef;
1268     Local<FunctionRef> func = objRef->Get(vm, StringRef::NewFromUtf8(vm, "SetPrivateGreeting"));
1269     Local<JSValueRef> argv [1] = {priGreeting};
1270     func->Call(vm, objRef, argv, 1);
1271 }
1272 
1273 /* // 非静态函数调用。 ts:
1274  * Greet(): string
1275  */
Greet(EcmaVM * vm,Local<Greeter> thisRef)1276 Local<StringRef> Greeter::Greet(EcmaVM *vm, Local<Greeter> thisRef)
1277 {
1278     Local<ObjectRef> objRef = thisRef;
1279     Local<FunctionRef> func = objRef->Get(vm, StringRef::NewFromUtf8(vm, "Greet"));
1280     return func->Call(vm, objRef, nullptr, 0);
1281 }
1282 
1283 /* // 静态函数的调用。 ts:
1284  * static StandardGreeting(): string
1285  */
StandardGreeting(EcmaVM * vm)1286 Local<StringRef> Greeter::StandardGreeting(EcmaVM *vm)
1287 {
1288     // 获取类函数。
1289     Local<FunctionRef> claFunc = Greeter::GetClassFunction(vm);
1290     // 获取函数
1291     Local<FunctionRef> func = claFunc->Get(vm, StringRef::NewFromUtf8(vm, "StandardGreeting"));
1292     // 调用函数
1293     return func->Call(vm, JSValueRef::Undefined(vm), nullptr, 0);
1294 }
1295 
1296 /* // 静态函数的调用。ts:
1297  * static StandardPosition(): string
1298  */
StandardPosition(EcmaVM * vm)1299 Local<StringRef> Greeter::StandardPosition(EcmaVM *vm)
1300 {
1301     // 获取类函数。
1302     Local<FunctionRef> claFunc = Greeter::GetClassFunction(vm);
1303     // 获取函数
1304     Local<FunctionRef> func = claFunc->Get(vm, StringRef::NewFromUtf8(vm, "StandardPosition"));
1305     // 调用函数
1306     return func->Call(vm, JSValueRef::Undefined(vm), nullptr, 0);
1307 }
1308 
1309 /* 类的调用测试: ts:
1310  * let greeter1: Greeter = new Greeter("everyone");
1311  *
1312  * // 非静态函数调用
1313  * console.log(greeter1.Greet());
1314  *
1315  * greeter1.SetPrivateGreeting("vip");
1316  * console.log(greeter1.Greet());
1317  *
1318  * greeter1.SetPrivateGreeting("");
1319  * console.log(greeter1.Greet());
1320  *
1321  * // 修改变量
1322  * greeter1.greeting = "";
1323  * console.log(greeter1.Greet());
1324  *
1325  * // 静态函数调用。
1326  * console.log(Greeter.StandardGreeting());
1327  * console.log(Greeter.StandardPosition());
1328  *
1329  * // 修改静态变量。
1330  * Greeter.position = "house";
1331  * console.log(Greeter.StandardPosition());
1332  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo5_class_test)1333 HWTEST_F_L0(JSNApiSampleTest, sample_demo5_class_test)
1334 {
1335     GTEST_LOG_(INFO) << "sample_demo5_class_test =======================================";
1336     LocalScope scope(vm_);
1337     Local<Greeter> greeter1 = Greeter::New(vm_, StringRef::NewFromUtf8(vm_, "everyone"));
1338     // 非静态函数调用
1339     GTEST_LOG_(INFO) << Greeter::Greet(vm_, greeter1)->ToString(vm_);
1340     Greeter::SetPrivateGreeting(vm_, greeter1, StringRef::NewFromUtf8(vm_, "vip"));
1341     GTEST_LOG_(INFO) << Greeter::Greet(vm_, greeter1)->ToString(vm_);
1342     Greeter::SetPrivateGreeting(vm_, greeter1, JSValueRef::Undefined(vm_));
1343     GTEST_LOG_(INFO) << Greeter::Greet(vm_, greeter1)->ToString(vm_);
1344     // 修改变量
1345     Local<ObjectRef> objRef1 = greeter1;
1346     objRef1->Set(vm_, StringRef::NewFromUtf8(vm_, "greeting"), JSValueRef::Undefined(vm_));
1347     GTEST_LOG_(INFO) << Greeter::Greet(vm_, greeter1)->ToString(vm_);
1348 
1349     // 静态函数调用。
1350     GTEST_LOG_(INFO) << Greeter::StandardGreeting(vm_)->ToString(vm_);
1351     GTEST_LOG_(INFO) << Greeter::StandardPosition(vm_)->ToString(vm_);
1352 
1353     // 修改静态变量。
1354     Local<FunctionRef> classFunc = Greeter::GetClassFunction(vm_);
1355     classFunc->Set(vm_, StringRef::NewFromUtf8(vm_, "position"), StringRef::NewFromUtf8(vm_, "house"));
1356 
1357     GTEST_LOG_(INFO) << Greeter::StandardPosition(vm_)->ToString(vm_);
1358     GTEST_LOG_(INFO) << "sample_demo5_class_test =======================================";
1359 }
1360 
1361 /* demo6 多态 ts:
1362  * // 基类
1363  * class Derive {
1364  * baseNum: number = 1
1365  * constructor(num: number){
1366  * this.baseNum = num
1367  * }
1368  * Compute(): number {
1369  * return this.baseNum
1370  * }
1371  * }
1372  * // 子类1
1373  * class DeriveDouble extends Derive {
1374  * constructor(num: number){
1375  * super(num);
1376  * }
1377  * Compute() : number {
1378  * return this.baseNum * 2
1379  * }
1380  * }
1381  * // 子类2
1382  * class DerivedTriple extends Derive {
1383  * constructor(num: number){
1384  * super(num);
1385  * }
1386  * Compute() : number {
1387  * return this.baseNum * 3
1388  * }
1389  * }
1390  *
1391  * // 测试:
1392  * let d1: Derive;
1393  * let d2: Derive;
1394  * let d3: Derive;
1395  * d1 = new Derive(5);//新建基类。
1396  * d2 = new DeriveDouble(5);//新建子类。
1397  * d3 = new DerivedTriple(5);//新建子类。
1398  * let i1:number = d1.Compute();
1399  * let i2:number = d2.Compute();
1400  * let i3:number = d3.Compute();
1401  * console.log(i1);
1402  * console.log(i2);
1403  * console.log(i3);
1404  */
1405 
1406 /* 基类 ts:
1407  * class Derive {
1408  * baseNum: number = 1
1409  * constructor(num: number){
1410  * this.baseNum = num
1411  * }
1412  * Compute(): number {
1413  * return this.baseNum
1414  * }
1415  * }
1416  */
1417 class Derive {
1418 private:
1419     // 新建ClassFunction
1420     static Local<FunctionRef> NewClassFunction(EcmaVM *vm);
1421 
1422 public:
1423     // 获取ClassFunction
1424     static Local<FunctionRef> GetClassFunction(EcmaVM *vm);
1425     static Local<Derive> New(EcmaVM *vm, Local<NumberRef> num);
1426 
1427     static Local<NumberRef> Compute(EcmaVM *vm, Local<Derive> thisRef);
1428 
1429 private:
1430     const static std::string CLASS_NAME;
1431 };
1432 
1433 const std::string Derive::CLASS_NAME = "DeriveClass";
1434 
NewClassFunction(EcmaVM * vm)1435 Local<FunctionRef> Derive::NewClassFunction(EcmaVM *vm)
1436 {
1437     Local<FunctionRef> claFunc = FunctionRef::NewClassFunction(
1438         vm,
1439         // 构造函数调用
1440         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
1441             EcmaVM *vm = runtimeInfo->GetVM();
1442             LocalScope scope(vm);
1443             // 获取this
1444             Local<JSValueRef> jsThisRef = runtimeInfo->GetThisRef();
1445             Local<ObjectRef> thisRef = jsThisRef->ToObject(vm);
1446             // 获取参数。
1447             Local<JSValueRef> num = runtimeInfo->GetCallArgRef(0);
1448             // this.baseNum = num
1449             thisRef->Set(vm, StringRef::NewFromUtf8(vm, "baseNum"), num);
1450             return thisRef;
1451         },
1452         nullptr, nullptr);
1453     Local<JSValueRef> jsProto = claFunc->GetFunctionPrototype(vm);
1454     Local<ObjectRef> proto = jsProto->ToObject(vm);
1455     // 添加非静态变量
1456     proto->Set(vm, StringRef::NewFromUtf8(vm, "baseNum"), NumberRef::New(vm, 1));
1457     // 添加非静态函数
1458     proto->Set(vm, StringRef::NewFromUtf8(vm, "Compute"),
1459         FunctionRef::New(vm,
1460         // 函数体
1461         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
1462             EcmaVM *vm = runtimeInfo->GetVM();
1463             LocalScope scope(vm);
1464 
1465             // 获取this
1466             Local<JSValueRef> jsThisRef = runtimeInfo->GetThisRef();
1467             Local<ObjectRef> thisRef = jsThisRef->ToObject(vm);
1468 
1469             Local<JSValueRef> jsNum = thisRef->Get(vm, StringRef::NewFromUtf8(vm, "baseNum"));
1470             int num = jsNum->Int32Value(vm);
1471             return NumberRef::New(vm, num);
1472         }));
1473     // 设置类名。
1474     claFunc->SetName(vm, StringRef::NewFromUtf8(vm, Derive::CLASS_NAME.c_str()));
1475     return claFunc;
1476 }
1477 
GetClassFunction(EcmaVM * vm)1478 Local<FunctionRef> Derive::GetClassFunction(EcmaVM *vm)
1479 {
1480     Local<ObjectRef> globalObj = JSNApi::GetGlobalObject(vm);
1481     Local<JSValueRef> jsClaFunc = globalObj->Get(vm, StringRef::NewFromUtf8(vm, Derive::CLASS_NAME.c_str()));
1482     if (jsClaFunc->IsFunction(vm)) {
1483         return jsClaFunc;
1484     }
1485     Local<FunctionRef> claFunc = Derive::NewClassFunction(vm);
1486     // 添加到全局。
1487     globalObj->Set(vm, claFunc->GetName(vm), claFunc);
1488     return claFunc;
1489 }
1490 
New(EcmaVM * vm,Local<NumberRef> num)1491 Local<Derive> Derive::New(EcmaVM *vm, Local<NumberRef> num)
1492 {
1493     // 获取类函数。
1494     Local<FunctionRef> claFunc = Derive::GetClassFunction(vm);
1495     // 定义参数。
1496     Local<JSValueRef> argv[1] = {num};
1497     // 构造函数,构造对象。
1498     Local<JSValueRef> jsObj = claFunc->Constructor(vm, argv, 1);
1499     Local<ObjectRef> obj = jsObj->ToObject(vm);
1500     return obj;
1501 }
1502 
Compute(EcmaVM * vm,Local<Derive> thisRef)1503 Local<NumberRef> Derive::Compute(EcmaVM *vm, Local<Derive> thisRef)
1504 {
1505     Local<ObjectRef> objRef = thisRef;
1506     Local<FunctionRef> func = objRef->Get(vm, StringRef::NewFromUtf8(vm, "Compute"));
1507     return func->Call(vm, objRef, nullptr, 0);
1508 }
1509 
1510 /* 子类1 ts:
1511  * class DeriveDouble extends Base {
1512  * constructor(num: number){
1513  * super(num);
1514  * }
1515  * Compute() : number {
1516  * return this.baseNum * 2
1517  * }
1518  * }
1519  */
1520 class DeriveDouble : public Derive {
1521 private:
1522     DeriveDouble() = default;
1523     // 新建ClassFunction
1524     static Local<FunctionRef> NewClassFunction(EcmaVM *vm);
1525 
1526 public:
1527     // 获取ClassFunction
1528     static Local<FunctionRef> GetClassFunction(EcmaVM *vm);
1529     static Local<DeriveDouble> New(EcmaVM *vm, Local<NumberRef> num);
1530     ~DeriveDouble() = default;
1531 
1532 public:
1533     // 设置类名
1534     const static std::string CLASS_NAME;
1535 };
1536 
1537 const std::string DeriveDouble::CLASS_NAME = "DeriveDoubleClass";
1538 
NewClassFunction(EcmaVM * vm)1539 Local<FunctionRef> DeriveDouble::NewClassFunction(EcmaVM *vm)
1540 {
1541     Local<FunctionRef> claFunc = FunctionRef::NewClassFunction(
1542         vm,
1543         // 构造函数调用
1544         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
1545             EcmaVM *vm = runtimeInfo->GetVM();
1546             LocalScope scope(vm);
1547             // 获取参数。
1548             Local<JSValueRef> num = runtimeInfo->GetCallArgRef(0);
1549             // 获取this
1550             Local<JSValueRef> jsThisRef = runtimeInfo->GetThisRef();
1551             Local<ObjectRef> thisRef = jsThisRef->ToObject(vm);
1552             // 修改父类。
1553             thisRef->Set(vm, StringRef::NewFromUtf8(vm, "baseNum"), num);
1554             return thisRef;
1555         },
1556         nullptr, nullptr);
1557     // 设置类名。
1558     claFunc->SetName(vm, StringRef::NewFromUtf8(vm, DeriveDouble::CLASS_NAME.c_str()));
1559 
1560     // 添加非静态函数
1561     Local<ObjectRef> proto = claFunc->GetFunctionPrototype(vm)->ToObject(vm);
1562     proto->Set(vm, StringRef::NewFromUtf8(vm, "Compute"),
1563         FunctionRef::New(vm,
1564         // 函数体
1565         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
1566             EcmaVM *vm = runtimeInfo->GetVM();
1567             LocalScope scope(vm);
1568             // 获取this
1569             Local<JSValueRef> jsThisRef = runtimeInfo->GetThisRef();
1570             Local<ObjectRef> thisRef = jsThisRef->ToObject(vm);
1571             Local<JSValueRef> jsNum = thisRef->Get(vm, StringRef::NewFromUtf8(vm, "baseNum"));
1572             int num = jsNum->Int32Value(vm);
1573             int multiple = 2; // 函数功能,2倍返回。
1574             num *= multiple;
1575             return NumberRef::New(vm, num);
1576         }));
1577     // 父类。
1578     Local<FunctionRef> claFuncBase = Derive::GetClassFunction(vm);
1579     // 继承。
1580     claFunc->Inherit(vm, claFuncBase);
1581     return claFunc;
1582 }
1583 
GetClassFunction(EcmaVM * vm)1584 Local<FunctionRef> DeriveDouble::GetClassFunction(EcmaVM *vm)
1585 {
1586     Local<ObjectRef> globalObj = JSNApi::GetGlobalObject(vm);
1587     Local<JSValueRef> jsClaFunc = globalObj->Get(vm, StringRef::NewFromUtf8(vm, DeriveDouble::CLASS_NAME.c_str()));
1588     if (jsClaFunc->IsFunction(vm)) {
1589         return jsClaFunc;
1590     }
1591     Local<FunctionRef> claFunc = DeriveDouble::NewClassFunction(vm);
1592     globalObj->Set(vm, claFunc->GetName(vm), claFunc);
1593     return claFunc;
1594 }
1595 
New(EcmaVM * vm,Local<NumberRef> num)1596 Local<DeriveDouble> DeriveDouble::New(EcmaVM *vm, Local<NumberRef> num)
1597 {
1598     // 获取类函数。
1599     Local<FunctionRef> claFunc = DeriveDouble::GetClassFunction(vm);
1600     // 定义参数。
1601     Local<JSValueRef> argv[1] = {num};
1602     // 构造函数,构造对象。
1603     Local<JSValueRef> jsObj = claFunc->Constructor(vm, argv, 1);
1604     Local<ObjectRef> obj = jsObj->ToObject(vm);
1605     return obj;
1606 }
1607 
1608 /* 子类2 ts:
1609  * class DerivedTriple extends Derive {
1610  * constructor(num: number){
1611  * super(num);
1612  * }
1613  * Compute() : number {
1614  * return this.baseNum * 3
1615  * }
1616  * }
1617  */
1618 class DerivedTriple : public Derive {
1619 private:
1620     DerivedTriple() = default;
1621     // 新建ClassFunction
1622     static Local<FunctionRef> NewClassFunction(EcmaVM *vm);
1623 
1624 public:
1625     // 获取ClassFunction
1626     static Local<FunctionRef> GetClassFunction(EcmaVM *vm);
1627     static Local<DerivedTriple> New(EcmaVM *vm, Local<NumberRef> num);
1628     ~DerivedTriple() = default;
1629 
1630 public:
1631     // 设置类名
1632     const static std::string CLASS_NAME;
1633 };
1634 
1635 const std::string DerivedTriple::CLASS_NAME = "DerivedTripleClass";
1636 
NewClassFunction(EcmaVM * vm)1637 Local<FunctionRef> DerivedTriple::NewClassFunction(EcmaVM *vm)
1638 {
1639     Local<FunctionRef> claFunc = FunctionRef::NewClassFunction(
1640         vm,
1641         // 构造函数调用
1642         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
1643             EcmaVM *vm = runtimeInfo->GetVM();
1644             LocalScope scope(vm);
1645             // 获取参数。
1646             Local<JSValueRef> num = runtimeInfo->GetCallArgRef(0);
1647             // 获取this
1648             Local<JSValueRef> jsThisRef = runtimeInfo->GetThisRef();
1649             Local<ObjectRef> thisRef = jsThisRef->ToObject(vm);
1650             // 修改父类。
1651             thisRef->Set(vm, StringRef::NewFromUtf8(vm, "baseNum"), num);
1652             return thisRef;
1653         },
1654         nullptr, nullptr);
1655     // 设置类名。
1656     claFunc->SetName(vm, StringRef::NewFromUtf8(vm, DerivedTriple::CLASS_NAME.c_str()));
1657 
1658     // 添加非静态函数
1659     Local<ObjectRef> proto = claFunc->GetFunctionPrototype(vm)->ToObject(vm);
1660     proto->Set(vm, StringRef::NewFromUtf8(vm, "Compute"),
1661         FunctionRef::New(vm,
1662         // 函数体
1663         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
1664             EcmaVM *vm = runtimeInfo->GetVM();
1665             LocalScope scope(vm);
1666             // 获取this
1667             Local<JSValueRef> jsThisRef = runtimeInfo->GetThisRef();
1668             Local<ObjectRef> thisRef = jsThisRef->ToObject(vm);
1669             Local<JSValueRef> jsNum = thisRef->Get(vm, StringRef::NewFromUtf8(vm, "baseNum"));
1670             int num = jsNum->Int32Value(vm);
1671             int multiple = 3; // 函数功能,3倍返回。
1672             num *= multiple;
1673             return NumberRef::New(vm, num);
1674         }));
1675     // 父类。
1676     Local<FunctionRef> claFuncBase = Derive::GetClassFunction(vm);
1677     // 继承。
1678     claFunc->Inherit(vm, claFuncBase);
1679     return claFunc;
1680 }
1681 
GetClassFunction(EcmaVM * vm)1682 Local<FunctionRef> DerivedTriple::GetClassFunction(EcmaVM *vm)
1683 {
1684     Local<ObjectRef> globalObj = JSNApi::GetGlobalObject(vm);
1685     Local<JSValueRef> jsClaFunc = globalObj->Get(vm, StringRef::NewFromUtf8(vm, DerivedTriple::CLASS_NAME.c_str()));
1686     if (jsClaFunc->IsFunction(vm)) {
1687         return jsClaFunc;
1688     }
1689     Local<FunctionRef> claFunc = DerivedTriple::NewClassFunction(vm);
1690     globalObj->Set(vm, claFunc->GetName(vm), claFunc);
1691     return claFunc;
1692 }
1693 
New(EcmaVM * vm,Local<NumberRef> num)1694 Local<DerivedTriple> DerivedTriple::New(EcmaVM *vm, Local<NumberRef> num)
1695 {
1696     // 获取类函数。
1697     Local<FunctionRef> claFunc = DerivedTriple::GetClassFunction(vm);
1698     // 定义参数。
1699     Local<JSValueRef> argv[1] = {num};
1700     // 构造函数,构造对象。
1701     Local<JSValueRef> jsObj = claFunc->Constructor(vm, argv, 1);
1702     Local<ObjectRef> obj = jsObj->ToObject(vm);
1703     return obj;
1704 }
1705 
1706 /* 测试。ts:
1707  * let d1: Derive;
1708  * let d2: Derive;
1709  * let d3: Derive;
1710  * d1 = new Derive(5);//新建基类。
1711  * d2 = new DeriveDouble(5);//新建子类。
1712  * d3 = new DerivedTriple(5);//新建子类。
1713  * let i1:number = d1.Compute();
1714  * let i2:number = d2.Compute();
1715  * let i3:number = d3.Compute();
1716  * console.log(i1);
1717  * console.log(i2);
1718  * console.log(i3);
1719  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo6_polymorphic_test)1720 HWTEST_F_L0(JSNApiSampleTest, sample_demo6_polymorphic_test)
1721 {
1722     GTEST_LOG_(INFO) << "sample_demo6_polymorphic_test =======================================";
1723     LocalScope scope(vm_);
1724 
1725     int num = 5;
1726 
1727     Local<Derive> d1 = Derive::New(vm_, NumberRef::New(vm_, num));
1728     Local<Derive> d2 = DeriveDouble::New(vm_, NumberRef::New(vm_, num));
1729     Local<Derive> d3 = DerivedTriple::New(vm_, NumberRef::New(vm_, num));
1730 
1731     Local<NumberRef> i1 = Derive::Compute(vm_, d1);
1732     Local<NumberRef> i2 = Derive::Compute(vm_, d2);
1733     Local<NumberRef> i3 = Derive::Compute(vm_, d3);
1734 
1735     GTEST_LOG_(INFO) << "i1 = " << i1->Int32Value(vm_);
1736     GTEST_LOG_(INFO) << "i2 = " << i2->Int32Value(vm_);
1737     GTEST_LOG_(INFO) << "i3 = " << i3->Int32Value(vm_);
1738 
1739     GTEST_LOG_(INFO) << "sample_demo6_polymorphic_test =======================================";
1740 }
1741 
1742 /* demo7 数组的使用 */
HWTEST_F_L0(JSNApiSampleTest,sample_ArrayRef_Int)1743 HWTEST_F_L0(JSNApiSampleTest, sample_ArrayRef_Int)
1744 {
1745     LocalScope scope(vm_);
1746     uint32_t length = 5; // array length = 5
1747     Local<ArrayRef> arrayObject = ArrayRef::New(vm_, length);
1748     uint32_t arrayLength = arrayObject->Length(vm_);
1749     uint32_t index = 1; // array index = 0
1750     for (int i = 0; i < (int)arrayLength; i++) {
1751         Local<IntegerRef> intValue = IntegerRef::New(vm_, i * 10);
1752         ArrayRef::SetValueAt(vm_, arrayObject, i, intValue);
1753         GTEST_LOG_(INFO) << "sample_setIntValue_index_" << i << ": " << intValue->Value();
1754     }
1755     Local<IntegerRef> resultInt = ArrayRef::GetValueAt(vm_, arrayObject, index);
1756     GTEST_LOG_(INFO) << "sample_getIntValue_index_1: " << resultInt->Value();
1757     int inputInt = 99; // int data = 99
1758     Local<IntegerRef> intValue = IntegerRef::New(vm_, inputInt);
1759     bool setResult = ArrayRef::SetValueAt(vm_, arrayObject, arrayLength, intValue);
1760     GTEST_LOG_(INFO) << "sample_setIntValue_index_5: " << intValue->Value() << " setResult: " << setResult;
1761     int changedInt = 66; // change data = 66
1762     Local<IntegerRef> changedIntValue = IntegerRef::New(vm_, changedInt);
1763     ArrayRef::SetValueAt(vm_, arrayObject, index, changedIntValue);
1764     GTEST_LOG_(INFO) << "sample_changedIntValue_index_1: " << changedIntValue->Value();
1765     Local<IntegerRef> resultChangedInt = ArrayRef::GetValueAt(vm_, arrayObject, index);
1766     GTEST_LOG_(INFO) << "sample_getChangedIntValue_index_1: " << resultChangedInt->Value();
1767     for (int i = 0; i < (int)arrayLength; i++) {
1768         Local<IntegerRef> printInt = ArrayRef::GetValueAt(vm_, arrayObject, i);
1769         GTEST_LOG_(INFO) << "sample_printIntValue_index_" << i << ": " << printInt->Value();
1770     }
1771 }
1772 
HWTEST_F_L0(JSNApiSampleTest,sample_ArrayRef_Bool)1773 HWTEST_F_L0(JSNApiSampleTest, sample_ArrayRef_Bool)
1774 {
1775     LocalScope scope(vm_);
1776     uint32_t length = 5; // array length = 5
1777     Local<ArrayRef> arrayObject = ArrayRef::New(vm_, length);
1778     uint32_t arrayLength = arrayObject->Length(vm_);
1779     bool inputBool = true; // bool data = true
1780     uint32_t index = 0;    // array index = 0
1781     Local<BooleanRef> boolValue = BooleanRef::New(vm_, inputBool);
1782     for (int i = 0; i < (int)arrayLength; i++) {
1783         ArrayRef::SetValueAt(vm_, arrayObject, i, boolValue);
1784         GTEST_LOG_(INFO) << "sample_setBoolValue_index_" << i << ": " << boolValue->Value();
1785     }
1786     Local<BooleanRef> resultBool = ArrayRef::GetValueAt(vm_, arrayObject, index);
1787     GTEST_LOG_(INFO) << "sample_getBoolValue_index_0: " << resultBool->Value();
1788     bool setResult = ArrayRef::SetValueAt(vm_, arrayObject, arrayLength, boolValue);
1789     GTEST_LOG_(INFO) << "sample_setBoolValue_index_5: " << boolValue->Value() << " setResult: " << setResult;
1790     bool changedBool = false; // change data = false
1791     Local<BooleanRef> changedBoolValue = BooleanRef::New(vm_, changedBool);
1792     ArrayRef::SetValueAt(vm_, arrayObject, index, changedBoolValue);
1793     GTEST_LOG_(INFO) << "sample_changedBoolValue_index_0: " << changedBoolValue->Value();
1794     Local<BooleanRef> resultChangedBool = ArrayRef::GetValueAt(vm_, arrayObject, index);
1795     GTEST_LOG_(INFO) << "sample_getChangedBoolValue_index_0: " << resultChangedBool->Value();
1796     for (int i = 0; i < (int)arrayLength; i++) {
1797         Local<BooleanRef> printBool = ArrayRef::GetValueAt(vm_, arrayObject, i);
1798         GTEST_LOG_(INFO) << "sample_printBoolValue_index_" << i << ": " << printBool->Value();
1799     }
1800 }
1801 
HWTEST_F_L0(JSNApiSampleTest,sample_ArrayRef_Number)1802 HWTEST_F_L0(JSNApiSampleTest, sample_ArrayRef_Number)
1803 {
1804     LocalScope scope(vm_);
1805     uint32_t length = 5; // array length = 5
1806     Local<ArrayRef> arrayObject = ArrayRef::New(vm_, length);
1807     uint32_t arrayLength = arrayObject->Length(vm_);
1808     uint32_t inputNumber = 40; // number data = 40
1809     uint32_t index = 0;        // array index = 0
1810     Local<NumberRef> numberValue = NumberRef::New(vm_, inputNumber);
1811     for (int i = 0; i < (int)arrayLength; i++) {
1812         ArrayRef::SetValueAt(vm_, arrayObject, i, numberValue);
1813         GTEST_LOG_(INFO) << "sample_setNumberValue_index_" << i << ": " << numberValue->Value();
1814     }
1815     Local<NumberRef> resultNumber = ArrayRef::GetValueAt(vm_, arrayObject, index);
1816     GTEST_LOG_(INFO) << "sample_getNumberValue_index_0: " << resultNumber->Value();
1817     bool setResult = ArrayRef::SetValueAt(vm_, arrayObject, arrayLength, numberValue);
1818     GTEST_LOG_(INFO) << "sample_setNumberValue_index_5: " << numberValue->Value() << " setResult: " << setResult;
1819     uint32_t changedNumber = 50; // change data = 50
1820     Local<NumberRef> changedNumberValue = NumberRef::New(vm_, changedNumber);
1821     ArrayRef::SetValueAt(vm_, arrayObject, index, changedNumberValue);
1822     GTEST_LOG_(INFO) << "sample_changedNumberValue_index_0: " << changedNumberValue->Value();
1823     Local<NumberRef> resultChangedNumber = ArrayRef::GetValueAt(vm_, arrayObject, index);
1824     GTEST_LOG_(INFO) << "sample_getChangedNumberValue_index_0: " << resultChangedNumber->Value();
1825     for (int i = 0; i < (int)arrayLength; i++) {
1826         Local<NumberRef> printNumber = ArrayRef::GetValueAt(vm_, arrayObject, i);
1827         GTEST_LOG_(INFO) << "sample_printNumberValue_index_" << i << ": " << printNumber->Value();
1828     }
1829 }
1830 
HWTEST_F_L0(JSNApiSampleTest,sample_ArrayRef_String)1831 HWTEST_F_L0(JSNApiSampleTest, sample_ArrayRef_String)
1832 {
1833     LocalScope scope(vm_);
1834     uint32_t length = 5; // array length = 5
1835     Local<ArrayRef> arrayObject = ArrayRef::New(vm_, length);
1836     uint32_t arrayLength = arrayObject->Length(vm_);
1837     std::string inputString = "Sample Test";
1838     uint32_t index = 0; // array index = 0
1839     Local<StringRef> stringValue = StringRef::NewFromUtf8(vm_, inputString.c_str());
1840     for (int i = 0; i < (int)arrayLength; i++) {
1841         ArrayRef::SetValueAt(vm_, arrayObject, i, stringValue);
1842         char setBuffer[20];
1843         stringValue->WriteUtf8(vm_, setBuffer, inputString.length());
1844         std::string result(setBuffer);
1845         GTEST_LOG_(INFO) << "sample_setStringValue_index_" << i << ": " << result;
1846         memset_s(setBuffer, sizeof(setBuffer), 0, sizeof(setBuffer));
1847     }
1848     Local<StringRef> resultString = ArrayRef::GetValueAt(vm_, arrayObject, index);
1849     char getBuffer[20];
1850     resultString->WriteUtf8(vm_, getBuffer, inputString.length());
1851     std::string getResult(getBuffer);
1852     GTEST_LOG_(INFO) << "sample_getStringValue_index_0: " << getResult;
1853     bool setResult = ArrayRef::SetValueAt(vm_, arrayObject, arrayLength, stringValue);
1854     GTEST_LOG_(INFO) << "sample_setStringValue_index_5"
1855                      << " setResult: " << setResult;
1856     std::string changedString = "Change Test";
1857     Local<StringRef> changedStringValue = StringRef::NewFromUtf8(vm_, changedString.c_str());
1858     ArrayRef::SetValueAt(vm_, arrayObject, index, changedStringValue);
1859     Local<StringRef> resultChangedString = ArrayRef::GetValueAt(vm_, arrayObject, index);
1860     char changedBuffer[20];
1861     resultChangedString->WriteUtf8(vm_, changedBuffer, changedString.length());
1862     std::string changedResult(changedBuffer);
1863     GTEST_LOG_(INFO) << "sample_getChangedStringValue_index_0: " << changedResult;
1864     for (int i = 0; i < (int)arrayLength; i++) {
1865         Local<StringRef> printString = ArrayRef::GetValueAt(vm_, arrayObject, i);
1866         char printBuffer[20];
1867         printString->WriteUtf8(vm_, printBuffer, inputString.length());
1868         std::string printResult(printBuffer);
1869         GTEST_LOG_(INFO) << "sample_printStringValue_index_" << i << ": " << printResult;
1870         memset_s(printBuffer, sizeof(printBuffer), 0, sizeof(printBuffer));
1871     }
1872 }
1873 
HWTEST_F_L0(JSNApiSampleTest,sample_TypedArrayRef_Int8Array)1874 HWTEST_F_L0(JSNApiSampleTest, sample_TypedArrayRef_Int8Array)
1875 {
1876     LocalScope scope(vm_);
1877     const int32_t length = 15; // arraybuffer length = 15
1878     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
1879     int32_t arrayLength = arrayBuffer->ByteLength(vm_);
1880     int8_t *ptr = (int8_t *)arrayBuffer->GetBuffer(vm_);
1881     for (int i = 0; i < arrayLength; i++) {
1882         *ptr = int8_t(i + 10);
1883         ptr++;
1884     }
1885     int32_t byteOffset = 5;      // byte offset = 5
1886     int32_t int8ArrayLength = 6; // array length = 6
1887     Local<Int8ArrayRef> typedArray = Int8ArrayRef::New(vm_, arrayBuffer, byteOffset, int8ArrayLength);
1888     GTEST_LOG_(INFO) << "sample_Int8Array_byteLength : " << typedArray->ByteLength(vm_);
1889     GTEST_LOG_(INFO) << "sample_Int8Array_byteOffset : " << typedArray->ByteOffset(vm_);
1890     GTEST_LOG_(INFO) << "sample_Int8Array_arrayLength : " << typedArray->ArrayLength(vm_);
1891     int8_t *result = (int8_t *)typedArray->GetArrayBuffer(vm_)->GetBuffer(vm_);
1892     for (int i = 0; i < int8ArrayLength; i++) {
1893         int value = int8_t(*result);
1894         GTEST_LOG_(INFO) << "sample_Int8Array_getInt8ArrayValue : " << value;
1895         result++;
1896     }
1897 }
1898 
HWTEST_F_L0(JSNApiSampleTest,sample_TypedArrayRef_Uint8Array)1899 HWTEST_F_L0(JSNApiSampleTest, sample_TypedArrayRef_Uint8Array)
1900 {
1901     LocalScope scope(vm_);
1902     const int32_t length = 15; // arraybuffer length = 15
1903     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
1904     int32_t arrayLength = arrayBuffer->ByteLength(vm_);
1905     uint8_t *ptr = (uint8_t *)arrayBuffer->GetBuffer(vm_);
1906     for (int i = 0; i < arrayLength; i++) {
1907         *ptr = uint8_t(i + 10);
1908         ptr++;
1909     }
1910     int32_t byteOffset = 5;       // byte offset = 5
1911     int32_t Uint8ArrayLength = 6; // array length = 6
1912     Local<Uint8ArrayRef> typedArray = Uint8ArrayRef::New(vm_, arrayBuffer, byteOffset, Uint8ArrayLength);
1913     GTEST_LOG_(INFO) << "sample_Uint8Array_byteLength : " << typedArray->ByteLength(vm_);
1914     GTEST_LOG_(INFO) << "sample_Uint8Array_byteOffset : " << typedArray->ByteOffset(vm_);
1915     GTEST_LOG_(INFO) << "sample_Uint8Array_arrayLength : " << typedArray->ArrayLength(vm_);
1916     uint8_t *result = (uint8_t *)typedArray->GetArrayBuffer(vm_)->GetBuffer(vm_);
1917     for (int i = 0; i < Uint8ArrayLength; i++) {
1918         int value = uint8_t(*result);
1919         GTEST_LOG_(INFO) << "sample_Uint8Array_getUint8ArrayValue : " << value;
1920         result++;
1921     }
1922 }
1923 
HWTEST_F_L0(JSNApiSampleTest,sample_TypedArrayRef_Uint8ClampedArray)1924 HWTEST_F_L0(JSNApiSampleTest, sample_TypedArrayRef_Uint8ClampedArray)
1925 {
1926     LocalScope scope(vm_);
1927     const int32_t length = 15; // arraybuffer length = 15
1928     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
1929     int32_t arrayLength = arrayBuffer->ByteLength(vm_);
1930     uint8_t *ptr = (uint8_t *)arrayBuffer->GetBuffer(vm_);
1931     for (int i = 0; i < arrayLength; i++) {
1932         *ptr = uint8_t(i + 10);
1933         ptr++;
1934     }
1935     int32_t byteOffset = 5;     // byte offset = 5
1936     int32_t uint8ArrLength = 6; // array length = 6
1937     Local<Uint8ClampedArrayRef> typedArray = Uint8ClampedArrayRef::New(vm_, arrayBuffer, byteOffset, uint8ArrLength);
1938     GTEST_LOG_(INFO) << "sample_Uint8ClampedArray_byteLength : " << typedArray->ByteLength(vm_);
1939     GTEST_LOG_(INFO) << "sample_Uint8ClampedArray_byteOffset : " << typedArray->ByteOffset(vm_);
1940     GTEST_LOG_(INFO) << "sample_Uint8ClampedArray_arrayLength : " << typedArray->ArrayLength(vm_);
1941     uint8_t *result = (uint8_t *)typedArray->GetArrayBuffer(vm_)->GetBuffer(vm_);
1942     for (int i = 0; i < uint8ArrLength; i++) {
1943         int value = uint8_t(*result);
1944         GTEST_LOG_(INFO) << "sample_Uint8ClampedArray_getUint8ClampedArrayValue : " << value;
1945         result++;
1946     }
1947 }
1948 
HWTEST_F_L0(JSNApiSampleTest,sample_TypedArrayRef_Int16Array)1949 HWTEST_F_L0(JSNApiSampleTest, sample_TypedArrayRef_Int16Array)
1950 {
1951     LocalScope scope(vm_);
1952     const int32_t length = 30; // arraybuffer length = 30
1953     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
1954     int32_t arrayLength = arrayBuffer->ByteLength(vm_);
1955     int16_t *ptr = (int16_t *)arrayBuffer->GetBuffer(vm_);
1956     for (int i = 0; i < arrayLength / 2; i++) {
1957         *ptr = int16_t(i + 10);
1958         ptr++;
1959     }
1960     int32_t byteOffset = 4;       // byte offset = 4
1961     int32_t int16ArrayLength = 6; // array length = 6
1962     Local<Int16ArrayRef> typedArray = Int16ArrayRef::New(vm_, arrayBuffer, byteOffset, int16ArrayLength);
1963     GTEST_LOG_(INFO) << "sample_Int16Array_byteLength : " << typedArray->ByteLength(vm_);
1964     GTEST_LOG_(INFO) << "sample_Int16Array_byteOffset : " << typedArray->ByteOffset(vm_);
1965     GTEST_LOG_(INFO) << "sample_Int16Array_arrayLength : " << typedArray->ArrayLength(vm_);
1966     int16_t *result = (int16_t *)typedArray->GetArrayBuffer(vm_)->GetBuffer(vm_);
1967     for (int i = 0; i < int16ArrayLength; i++) {
1968         int value = int16_t(*result);
1969         GTEST_LOG_(INFO) << "sample_Int16Array_getInt16ArrayValue : " << value;
1970         result++;
1971     }
1972 }
1973 
HWTEST_F_L0(JSNApiSampleTest,sample_TypedArrayRef_Uint16Array)1974 HWTEST_F_L0(JSNApiSampleTest, sample_TypedArrayRef_Uint16Array)
1975 {
1976     LocalScope scope(vm_);
1977     const int32_t length = 30; // arraybuffer length = 30
1978     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
1979     int32_t arrayLength = arrayBuffer->ByteLength(vm_);
1980     uint16_t *ptr = (uint16_t *)arrayBuffer->GetBuffer(vm_);
1981     for (int i = 0; i < arrayLength / 2; i++) {
1982         *ptr = uint16_t(i + 10);
1983         ptr++;
1984     }
1985     int32_t byteOffset = 4;        // byte offset = 4
1986     int32_t uint16ArrayLength = 6; // array length = 6
1987     Local<Uint16ArrayRef> typedArray = Uint16ArrayRef::New(vm_, arrayBuffer, byteOffset, uint16ArrayLength);
1988     GTEST_LOG_(INFO) << "sample_Uint16Array_byteLength : " << typedArray->ByteLength(vm_);
1989     GTEST_LOG_(INFO) << "sample_Uint16Array_byteOffset : " << typedArray->ByteOffset(vm_);
1990     GTEST_LOG_(INFO) << "sample_Uint16Array_arrayLength : " << typedArray->ArrayLength(vm_);
1991     uint16_t *result = (uint16_t *)typedArray->GetArrayBuffer(vm_)->GetBuffer(vm_);
1992     for (int i = 0; i < uint16ArrayLength; i++) {
1993         int value = uint16_t(*result);
1994         GTEST_LOG_(INFO) << "sample_Uint16Array_getUint16ArrayValue : " << value;
1995         result++;
1996     }
1997 }
1998 
HWTEST_F_L0(JSNApiSampleTest,sample_TypedArrayRef_Int32Array)1999 HWTEST_F_L0(JSNApiSampleTest, sample_TypedArrayRef_Int32Array)
2000 {
2001     LocalScope scope(vm_);
2002     const int32_t length = 32; // arraybuffer length = 32
2003     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
2004     int32_t arrayLength = arrayBuffer->ByteLength(vm_);
2005     int32_t *ptr = (int32_t *)arrayBuffer->GetBuffer(vm_);
2006     for (int i = 0; i < arrayLength / 4; i++) {
2007         *ptr = int32_t(i + 10);
2008         ptr++;
2009     }
2010     int32_t byteOffset = 4;       // byte offset = 4
2011     int32_t int32ArrayLength = 6; // array length = 6
2012     Local<Int32ArrayRef> typedArray = Int32ArrayRef::New(vm_, arrayBuffer, byteOffset, int32ArrayLength);
2013     GTEST_LOG_(INFO) << "sample_Int32Array_byteLength : " << typedArray->ByteLength(vm_);
2014     GTEST_LOG_(INFO) << "sample_Int32Array_byteOffset : " << typedArray->ByteOffset(vm_);
2015     GTEST_LOG_(INFO) << "sample_Int32Array_arrayLength : " << typedArray->ArrayLength(vm_);
2016     int32_t *result = (int32_t *)typedArray->GetArrayBuffer(vm_)->GetBuffer(vm_);
2017     for (int i = 0; i < int32ArrayLength; i++) {
2018         int value = int32_t(*result);
2019         GTEST_LOG_(INFO) << "sample_Int32Array_getInt32ArrayValue : " << value;
2020         result++;
2021     }
2022 }
2023 
HWTEST_F_L0(JSNApiSampleTest,sample_TypedArrayRef_Uint32Array)2024 HWTEST_F_L0(JSNApiSampleTest, sample_TypedArrayRef_Uint32Array)
2025 {
2026     LocalScope scope(vm_);
2027     const int32_t length = 32; // arraybuffer length = 32
2028     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
2029     int32_t arrayLength = arrayBuffer->ByteLength(vm_);
2030     uint32_t *ptr = (uint32_t *)arrayBuffer->GetBuffer(vm_);
2031     for (int i = 0; i < arrayLength / 4; i++) {
2032         *ptr = uint32_t(i + 10);
2033         ptr++;
2034     }
2035     int32_t byteOffset = 4;        // byte offset = 4
2036     int32_t uint32ArrayLength = 6; // array length = 6
2037     Local<Uint32ArrayRef> typedArray = Uint32ArrayRef::New(vm_, arrayBuffer, byteOffset, uint32ArrayLength);
2038     GTEST_LOG_(INFO) << "sample_Uint32Array_byteLength : " << typedArray->ByteLength(vm_);
2039     GTEST_LOG_(INFO) << "sample_Uint32Array_byteOffset : " << typedArray->ByteOffset(vm_);
2040     GTEST_LOG_(INFO) << "sample_Uint32Array_arrayLength : " << typedArray->ArrayLength(vm_);
2041     uint32_t *result = (uint32_t *)typedArray->GetArrayBuffer(vm_)->GetBuffer(vm_);
2042     for (int i = 0; i < uint32ArrayLength; i++) {
2043         int value = uint32_t(*result);
2044         GTEST_LOG_(INFO) << "sample_Uint32Array_getUint32ArrayValue : " << value;
2045         result++;
2046     }
2047 }
2048 
HWTEST_F_L0(JSNApiSampleTest,sample_TypedArrayRef_Float32Array)2049 HWTEST_F_L0(JSNApiSampleTest, sample_TypedArrayRef_Float32Array)
2050 {
2051     LocalScope scope(vm_);
2052     const int32_t length = 32; // arraybuffer length = 32
2053     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
2054     int32_t arrayLength = arrayBuffer->ByteLength(vm_);
2055     float *ptr = (float *)arrayBuffer->GetBuffer(vm_);
2056     for (int i = 0; i < arrayLength / 4; i++) {
2057         *ptr = float(i + 10);
2058         ptr++;
2059     }
2060     int32_t byteOffset = 4;         // byte offset = 4
2061     int32_t float32ArrayLength = 6; // array length = 6
2062     Local<Float32ArrayRef> typedArray = Float32ArrayRef::New(vm_, arrayBuffer, byteOffset, float32ArrayLength);
2063     GTEST_LOG_(INFO) << "sample_Float32Array_byteLength : " << typedArray->ByteLength(vm_);
2064     GTEST_LOG_(INFO) << "sample_Float32Array_byteOffset : " << typedArray->ByteOffset(vm_);
2065     GTEST_LOG_(INFO) << "sample_Float32Array_arrayLength : " << typedArray->ArrayLength(vm_);
2066     float *result = (float *)typedArray->GetArrayBuffer(vm_)->GetBuffer(vm_);
2067     for (int i = 0; i < float32ArrayLength; i++) {
2068         int value = float(*result);
2069         GTEST_LOG_(INFO) << "sample_Float32Array_getFloat32ArrayValue : " << value;
2070         result++;
2071     }
2072 }
2073 
HWTEST_F_L0(JSNApiSampleTest,sample_TypedArrayRef_Float64Array)2074 HWTEST_F_L0(JSNApiSampleTest, sample_TypedArrayRef_Float64Array)
2075 {
2076     LocalScope scope(vm_);
2077     const int32_t length = 64; // arraybuffer length = 64
2078     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
2079     int32_t arrayLength = arrayBuffer->ByteLength(vm_);
2080     double *ptr = (double *)arrayBuffer->GetBuffer(vm_);
2081     for (int i = 0; i < arrayLength / 8; i++) {
2082         *ptr = double(i + 10);
2083         ptr++;
2084     }
2085     int32_t byteOffset = 8;         // byte offset = 8
2086     int32_t float64ArrayLength = 6; // array length = 6
2087     Local<Float64ArrayRef> typedArray = Float64ArrayRef::New(vm_, arrayBuffer, byteOffset, float64ArrayLength);
2088     GTEST_LOG_(INFO) << "sample_Float64Array_byteLength : " << typedArray->ByteLength(vm_);
2089     GTEST_LOG_(INFO) << "sample_Float64Array_byteOffset : " << typedArray->ByteOffset(vm_);
2090     GTEST_LOG_(INFO) << "sample_Float64Array_arrayLength : " << typedArray->ArrayLength(vm_);
2091     double *result = (double *)typedArray->GetArrayBuffer(vm_)->GetBuffer(vm_);
2092     for (int i = 0; i < float64ArrayLength; i++) {
2093         int value = double(*result);
2094         GTEST_LOG_(INFO) << "sample_Float64Array_getFloat64ArrayValue : " << value;
2095         result++;
2096     }
2097 }
2098 
HWTEST_F_L0(JSNApiSampleTest,sample_TypedArrayRef_BigInt64Array)2099 HWTEST_F_L0(JSNApiSampleTest, sample_TypedArrayRef_BigInt64Array)
2100 {
2101     LocalScope scope(vm_);
2102     const int32_t length = 64; // arraybuffer length = 64
2103     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
2104     int32_t arrayLength = arrayBuffer->ByteLength(vm_);
2105     int64_t *ptr = (int64_t *)arrayBuffer->GetBuffer(vm_);
2106     for (int i = 0; i < arrayLength / 8; i++) {
2107         *ptr = int64_t(i * 100);
2108         ptr++;
2109     }
2110     int32_t byteOffset = 8;          // byte offset = 8
2111     int32_t bigInt64ArrayLength = 6; // array length = 6
2112     Local<BigInt64ArrayRef> typedArray = BigInt64ArrayRef::New(vm_, arrayBuffer, byteOffset, bigInt64ArrayLength);
2113     GTEST_LOG_(INFO) << "sample_BigInt64Array_byteLength : " << typedArray->ByteLength(vm_);
2114     GTEST_LOG_(INFO) << "sample_BigInt64Array_byteOffset : " << typedArray->ByteOffset(vm_);
2115     GTEST_LOG_(INFO) << "sample_BigInt64Array_arrayLength : " << typedArray->ArrayLength(vm_);
2116     int64_t *result = (int64_t *)typedArray->GetArrayBuffer(vm_)->GetBuffer(vm_);
2117     for (int i = 0; i < bigInt64ArrayLength; i++) {
2118         int value = int64_t(*result);
2119         GTEST_LOG_(INFO) << "sample_BigInt64Array_getBigInt64ArrayValue : " << value;
2120         result++;
2121     }
2122 }
2123 
HWTEST_F_L0(JSNApiSampleTest,sample_TypedArrayRef_BigUint64Array)2124 HWTEST_F_L0(JSNApiSampleTest, sample_TypedArrayRef_BigUint64Array)
2125 {
2126     LocalScope scope(vm_);
2127     const int32_t length = 64; // arraybuffer length = 64
2128     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
2129     int32_t arrayLength = arrayBuffer->ByteLength(vm_);
2130     uint64_t *ptr = (uint64_t *)arrayBuffer->GetBuffer(vm_);
2131     for (int i = 0; i < arrayLength / 8; i++) {
2132         *ptr = int64_t(i * 100);
2133         ptr++;
2134     }
2135     int32_t byteOffset = 8;           // byte offset = 8
2136     int32_t bigUint64ArrayLength = 6; // array length = 6
2137     Local<BigUint64ArrayRef> typedArray = BigUint64ArrayRef::New(vm_, arrayBuffer, byteOffset, bigUint64ArrayLength);
2138     GTEST_LOG_(INFO) << "sample_BigUint64Array_byteLength : " << typedArray->ByteLength(vm_);
2139     GTEST_LOG_(INFO) << "sample_BigUint64Array_byteOffset : " << typedArray->ByteOffset(vm_);
2140     GTEST_LOG_(INFO) << "sample_BigUint64Array_arrayLength : " << typedArray->ArrayLength(vm_);
2141     uint64_t *result = (uint64_t *)typedArray->GetArrayBuffer(vm_)->GetBuffer(vm_);
2142     for (int i = 0; i < bigUint64ArrayLength; i++) {
2143         int value = uint64_t(*result);
2144         GTEST_LOG_(INFO) << "sample_BigUint64Array_getBigUint64ArrayValue : " << value;
2145         result++;
2146     }
2147 }
2148 
HWTEST_F_L0(JSNApiSampleTest,sample_DataViewRef)2149 HWTEST_F_L0(JSNApiSampleTest, sample_DataViewRef)
2150 {
2151     LocalScope scope(vm_);
2152     const int32_t length = 15; // arraybuffer length = 15
2153     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
2154     int32_t byteOffset = 5;     // byte offset = 5
2155     int32_t dataViewLength = 7; // dataview length = 7
2156     Local<DataViewRef> dataView = DataViewRef::New(vm_, arrayBuffer, byteOffset, dataViewLength);
2157     GTEST_LOG_(INFO) << "sample_DataView_byteLength : " << dataView->ByteLength();
2158     GTEST_LOG_(INFO) << "sample_DataView_byteOffset : " << dataView->ByteOffset();
2159     GTEST_LOG_(INFO) << "sample_DataView_getArrayBuffer : " << dataView->GetArrayBuffer(vm_)->GetBuffer(vm_);
2160 }
2161 
HWTEST_F_L0(JSNApiSampleTest,sample_ArrayBuffer_New_Detach)2162 HWTEST_F_L0(JSNApiSampleTest, sample_ArrayBuffer_New_Detach)
2163 {
2164     LocalScope scope(vm_);
2165     const int32_t length = 32; // arraybuffer length = 32
2166     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
2167     int32_t arrayLength = arrayBuffer->ByteLength(vm_);
2168     GTEST_LOG_(INFO) << "sample_ArrayBuffer_byteLength : " << arrayLength;
2169     GTEST_LOG_(INFO) << "sample_ArrayBuffer_getArrayBuffer : " << arrayBuffer->GetBuffer(vm_);
2170     arrayBuffer->Detach(vm_);
2171     GTEST_LOG_(INFO) << "sample_ArrayBuffer_getDetachArrayBuffer : " << arrayBuffer->GetBuffer(vm_);
2172     bool result = arrayBuffer->IsDetach(vm_);
2173     GTEST_LOG_(INFO) << "sample_ArrayBuffer_getIsDetach : " << result;
2174 }
2175 
HWTEST_F_L0(JSNApiSampleTest,sample_ArrayBufferWithBuffer_New_Detach)2176 HWTEST_F_L0(JSNApiSampleTest, sample_ArrayBufferWithBuffer_New_Detach)
2177 {
2178     static bool isFree = false;
2179     struct Data {
2180         int32_t length;
2181     };
2182     const int32_t length = 5; // arraybuffer length = 5
2183     Data *data = new Data();
2184     data->length = length;
2185     NativePointerCallback deleter = [](void *env, void *buffer, void *data) -> void {
2186         delete[] reinterpret_cast<uint8_t *>(buffer);
2187         Data *currentData = reinterpret_cast<Data *>(data);
2188         delete currentData;
2189         isFree = true;
2190     };
2191     LocalScope scope(vm_);
2192     uint8_t *buffer = new uint8_t[length]();
2193     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, buffer, length, deleter, data);
2194     GTEST_LOG_(INFO) << "sample_ArrayBufferWithBuffer_byteLength : " << arrayBuffer->ByteLength(vm_);
2195     GTEST_LOG_(INFO) << "sample_ArrayBufferWithBuffer_getArrayBuffer : " << arrayBuffer->GetBuffer(vm_);
2196     arrayBuffer->Detach(vm_);
2197     GTEST_LOG_(INFO) << "sample_ArrayBufferWithBuffer_getDetachArrayBuffer : " << arrayBuffer->GetBuffer(vm_);
2198     bool result = arrayBuffer->IsDetach(vm_);
2199     GTEST_LOG_(INFO) << "sample_ArrayBufferWithBuffer_getIsDetach : " << result;
2200 }
2201 
HWTEST_F_L0(JSNApiSampleTest,sample_Buffer_New_GetBuffer)2202 HWTEST_F_L0(JSNApiSampleTest, sample_Buffer_New_GetBuffer)
2203 {
2204     LocalScope scope(vm_);
2205     const int32_t length = 5; // buffer length = 5
2206     Local<BufferRef> buffer = BufferRef::New(vm_, length);
2207     GTEST_LOG_(INFO) << "sample_Buffer_byteLength : " << buffer->ByteLength(vm_);
2208     GTEST_LOG_(INFO) << "sample_Buffer_getBuffer : " << buffer->GetBuffer(vm_);
2209 }
2210 
HWTEST_F_L0(JSNApiSampleTest,sample_BufferWithBuffer_New_GetBuffer)2211 HWTEST_F_L0(JSNApiSampleTest, sample_BufferWithBuffer_New_GetBuffer)
2212 {
2213     static bool isFree = false;
2214     struct Data {
2215         int32_t length;
2216     };
2217     const int32_t length = 5; // buffer length = 5
2218     Data *data = new Data();
2219     data->length = length;
2220     NativePointerCallback deleter = [](void *env, void *buffer, void *data) -> void {
2221         delete[] reinterpret_cast<uint8_t *>(buffer);
2222         Data *currentData = reinterpret_cast<Data *>(data);
2223         delete currentData;
2224         isFree = true;
2225     };
2226     LocalScope scope(vm_);
2227     uint8_t *buffer = new uint8_t[length]();
2228     Local<BufferRef> bufferObj = BufferRef::New(vm_, buffer, length, deleter, data);
2229     GTEST_LOG_(INFO) << "sample_bufferWithBuffer_byteLength : " << bufferObj->ByteLength(vm_);
2230     GTEST_LOG_(INFO) << "sample_bufferWithBuffer_getBuffer : " << bufferObj->GetBuffer(vm_);
2231 }
2232 
2233 /* domo8 异步操作。 ts:
2234  * new Promise(function (resolve, reject) {
2235  * var a = 0;
2236  * var b = 1;
2237  * if (b == 0) reject("Divide zero");
2238  * else resolve(a / b);
2239  * }).then(function (value) {
2240  * console.log("a / b = " + value);
2241  * }).catch(function (err) {
2242  * console.log(err);
2243  * }).finally(function () {
2244  * console.log("End");
2245  * });
2246  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo8_async_test_1)2247 HWTEST_F_L0(JSNApiSampleTest, sample_demo8_async_test_1)
2248 {
2249     GTEST_LOG_(INFO) << "sample_demo8_async_test_1 =======================================";
2250     LocalScope scope(vm_);
2251 
2252     Local<PromiseCapabilityRef> capability = PromiseCapabilityRef::New(vm_);
2253     capability->GetPromise(vm_)
2254         ->Then(vm_, FunctionRef::New(vm_,
2255         // 函数体
2256         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
2257             EcmaVM *vm = runtimeInfo->GetVM();
2258             LocalScope scope(vm);
2259             Local<JSValueRef> jsNum = runtimeInfo->GetCallArgRef(0);
2260             int num = jsNum->Int32Value(vm);
2261             // ts: console.log("a / b = " + value);
2262             GTEST_LOG_(INFO) << "a / b = " << num;
2263             return JSValueRef::Undefined(vm);
2264         }))
2265         ->Catch(vm_, FunctionRef::New(vm_,
2266         // 函数体
2267         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
2268             EcmaVM *vm = runtimeInfo->GetVM();
2269             LocalScope scope(vm);
2270             Local<JSValueRef> jsStr = runtimeInfo->GetCallArgRef(0);
2271             std::string err = jsStr->ToString(vm)->ToString(vm);
2272             // ts: console.log(err);
2273             GTEST_LOG_(INFO) << err;
2274             return JSValueRef::Undefined(vm);
2275         }))
2276         ->Finally(vm_, FunctionRef::New(vm_,
2277         // 函数体
2278         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
2279             EcmaVM *vm = runtimeInfo->GetVM();
2280             LocalScope scope(vm);
2281             // ts: console.log("End");
2282             GTEST_LOG_(INFO) << "End";
2283             return JSValueRef::Undefined(vm);
2284         }));
2285 
2286     int a = 0;
2287     int b = 0;
2288     if (b == 0) {
2289         capability->Reject(vm_, StringRef::NewFromUtf8(vm_, "Divide zero"));
2290     } else {
2291         capability->Resolve(vm_, NumberRef::New(vm_, int(a / b)));
2292     }
2293 
2294     GTEST_LOG_(INFO) << "sample_demo8_async_test_1 =======================================";
2295 }
2296 
2297 // JSValueRef转为字符串输出。
jsValue2String(EcmaVM * vm,Local<JSValueRef> & jsVal)2298 std::string jsValue2String(EcmaVM *vm, Local<JSValueRef> &jsVal)
2299 {
2300     if (jsVal->IsString(vm)) {
2301         return "type string, val : " + jsVal->ToString(vm)->ToString(vm);
2302     } else if (jsVal->IsNumber()) {
2303         return "type number, val : " + std::to_string(jsVal->Int32Value(vm));
2304     } else if (jsVal->IsBoolean()) {
2305         return "type bool, val : " + std::to_string(jsVal->BooleaValue(vm));
2306     } else if (jsVal->IsSymbol(vm)) {
2307         Local<SymbolRef> symbol = jsVal;
2308         return "type symbol, val : " + symbol->GetDescription(vm)->ToString(vm);
2309     } else {
2310         return "type other : " + jsVal->ToString(vm)->ToString(vm);
2311     }
2312 }
2313 
MapSetValue(EcmaVM * vm,Local<MapRef> & map,Local<JSValueRef> symbolKey)2314 void MapSetValue(EcmaVM *vm, Local<MapRef> &map, Local<JSValueRef> symbolKey)
2315 {
2316     map->Set(vm, StringRef::NewFromUtf8(vm, "key1"), StringRef::NewFromUtf8(vm, "val1"));
2317     int num2 = 222; // random number
2318     map->Set(vm, StringRef::NewFromUtf8(vm, "key2"), NumberRef::New(vm, num2));
2319     map->Set(vm, StringRef::NewFromUtf8(vm, "key3"), BooleanRef::New(vm, true));
2320     map->Set(vm, StringRef::NewFromUtf8(vm, "key4"), SymbolRef::New(vm, StringRef::NewFromUtf8(vm, "val4")));
2321     int num5 = 55; // random number
2322     map->Set(vm, IntegerRef::New(vm, num5), StringRef::NewFromUtf8(vm, "val5"));
2323     int num61 = 66;  // random number
2324     int num62 = 666; // random number
2325     map->Set(vm, IntegerRef::New(vm, num61), IntegerRef::New(vm, num62));
2326     map->Set(vm, BooleanRef::New(vm, true), StringRef::NewFromUtf8(vm, "val7"));
2327     map->Set(vm, symbolKey, StringRef::NewFromUtf8(vm, "val8"));
2328 }
2329 
MapGetValue(EcmaVM * vm,Local<MapRef> & map,Local<JSValueRef> symbolKey)2330 void MapGetValue(EcmaVM *vm, Local<MapRef> &map, Local<JSValueRef> symbolKey)
2331 {
2332     Local<JSValueRef> val1 = map->Get(vm, StringRef::NewFromUtf8(vm, "key1"));
2333     bool val1IsString = val1->IsString(vm);
2334     GTEST_LOG_(INFO) << "key1 : IsString:" << val1IsString << "    val:" << val1->ToString(vm)->ToString(vm);
2335 
2336     Local<JSValueRef> val2 = map->Get(vm, StringRef::NewFromUtf8(vm, "key2"));
2337     bool val2IsNumber = val2->IsNumber();
2338     GTEST_LOG_(INFO) << "key2 : IsNumber:" << val2IsNumber << "    val:" << val2->Int32Value(vm);
2339 
2340     Local<JSValueRef> val3 = map->Get(vm, StringRef::NewFromUtf8(vm, "key3"));
2341     bool val3IsBoolean = val3->IsBoolean();
2342     GTEST_LOG_(INFO) << "key3 : IsBoolean:" << val3IsBoolean << "    val:" << val3->BooleaValue(vm);
2343 
2344     Local<JSValueRef> val4 = map->Get(vm, StringRef::NewFromUtf8(vm, "key4"));
2345     bool val4IsSymbol = val4->IsSymbol(vm);
2346     Local<SymbolRef> val4Symbol = val4;
2347     GTEST_LOG_(INFO) << "key4 : IsSymbol:" << val4IsSymbol << "    val:"
2348                      << val4Symbol->GetDescription(vm)->ToString(vm);
2349 
2350     int num5 = 55; // random number
2351     Local<JSValueRef> val5 = map->Get(vm, IntegerRef::New(vm, num5));
2352     GTEST_LOG_(INFO) << "55 : " << val5->ToString(vm)->ToString(vm);
2353 
2354     int num6 = 66; // random number
2355     Local<JSValueRef> val6 = map->Get(vm, IntegerRef::New(vm, num6));
2356     GTEST_LOG_(INFO) << "66 : " << val6->Int32Value(vm);
2357     Local<JSValueRef> val7 = map->Get(vm, BooleanRef::New(vm, true));
2358     GTEST_LOG_(INFO) << "true : " << val7->ToString(vm)->ToString(vm);
2359 
2360     Local<JSValueRef> val8 = map->Get(vm, symbolKey);
2361     GTEST_LOG_(INFO) << "SymbolRef(key8)  : " << val8->ToString(vm)->ToString(vm);
2362 
2363     Local<JSValueRef> val82 = map->Get(vm, SymbolRef::New(vm, StringRef::NewFromUtf8(vm, "key8")));
2364     GTEST_LOG_(INFO) << "new SymbolRef(key8) is Undefined : " << val82->IsUndefined();
2365 
2366     int32_t size = map->GetSize(vm);
2367     GTEST_LOG_(INFO) << "size : " << size;
2368     int32_t totalElement = map->GetTotalElements(vm);
2369     GTEST_LOG_(INFO) << "total element : " << totalElement;
2370 
2371     for (int i = 0; i < size; ++i) {
2372         Local<JSValueRef> jsKey = map->GetKey(vm, i);
2373         Local<JSValueRef> jsVal = map->GetValue(vm, i);
2374         GTEST_LOG_(INFO) << "for map index : " << i << "    key : " << jsValue2String(vm, jsKey) << "    val : " <<
2375             jsValue2String(vm, jsVal);
2376     }
2377 }
2378 
MapIteratorGetValue(EcmaVM * vm,Local<MapRef> & map)2379 void MapIteratorGetValue(EcmaVM *vm, Local<MapRef> &map)
2380 {
2381     Local<MapIteratorRef> mapIter = MapIteratorRef::New(vm, map);
2382     ecmascript::EcmaRuntimeCallInfo *mapIterInfo = mapIter->GetEcmaRuntimeCallInfo(vm);
2383 
2384     Local<StringRef> kind = mapIter->GetKind(vm);
2385     GTEST_LOG_(INFO) << "Map Iterator kind : " << kind->ToString(vm);
2386 
2387     for (Local<ArrayRef> array = MapIteratorRef::Next(vm, mapIterInfo); array->IsArray(vm);
2388         array = MapIteratorRef::Next(vm, mapIterInfo)) {
2389         int index = mapIter->GetIndex() - 1;
2390         Local<JSValueRef> jsKey = ArrayRef::GetValueAt(vm, array, 0);
2391         Local<JSValueRef> jsVal = ArrayRef::GetValueAt(vm, array, 1);
2392         GTEST_LOG_(INFO) << "for map iterator index : " << index << "    key : " << jsValue2String(vm, jsKey) <<
2393             "    val : " << jsValue2String(vm, jsVal);
2394     }
2395 }
2396 
2397 /* demo9 Map,MapIterator 的操作。 */
HWTEST_F_L0(JSNApiSampleTest,sample_demo9_map_test_1_MapRef_MapIteratorRef)2398 HWTEST_F_L0(JSNApiSampleTest, sample_demo9_map_test_1_MapRef_MapIteratorRef)
2399 {
2400     GTEST_LOG_(INFO) << "sample_demo9_map_test_1_MapRef_MapIteratorRef =======================================";
2401     LocalScope scope(vm_);
2402 
2403     Local<MapRef> map = MapRef::New(vm_);
2404     Local<JSValueRef> symbolKey = SymbolRef::New(vm_, StringRef::NewFromUtf8(vm_, "key8"));
2405     MapSetValue(vm_, map, symbolKey);
2406     MapGetValue(vm_, map, symbolKey);
2407     MapIteratorGetValue(vm_, map);
2408     GTEST_LOG_(INFO) << "sample_demo9_map_test_1_MapRef_MapIteratorRef =======================================";
2409 }
2410 
2411 /* demo9 WeakMap 的操作。 */
HWTEST_F_L0(JSNApiSampleTest,sample_demo9_map_test_2_WeakMapref)2412 HWTEST_F_L0(JSNApiSampleTest, sample_demo9_map_test_2_WeakMapref)
2413 {
2414     GTEST_LOG_(INFO) << "sample_demo9_map_test_2_WeakMapref =======================================";
2415     LocalScope scope(vm_);
2416 
2417     Local<WeakMapRef> weakMap = WeakMapRef::New(vm_);
2418     weakMap->Set(vm_, StringRef::NewFromUtf8(vm_, "key1"), StringRef::NewFromUtf8(vm_, "val1"));
2419     int num2 = 222; // random number
2420     weakMap->Set(vm_, StringRef::NewFromUtf8(vm_, "key2"), NumberRef::New(vm_, num2));
2421     weakMap->Set(vm_, StringRef::NewFromUtf8(vm_, "key3"), BooleanRef::New(vm_, true));
2422     weakMap->Set(vm_, StringRef::NewFromUtf8(vm_, "key4"), SymbolRef::New(vm_, StringRef::NewFromUtf8(vm_, "val4")));
2423     weakMap->Set(vm_, IntegerRef::New(vm_, 55), StringRef::NewFromUtf8(vm_, "val5"));
2424     int num6 = 666; // random number
2425     weakMap->Set(vm_, IntegerRef::New(vm_, 66), IntegerRef::New(vm_, num6));
2426     weakMap->Set(vm_, BooleanRef::New(vm_, true), StringRef::NewFromUtf8(vm_, "val7"));
2427     Local<JSValueRef> key8 = SymbolRef::New(vm_, StringRef::NewFromUtf8(vm_, "key8"));
2428     weakMap->Set(vm_, key8, StringRef::NewFromUtf8(vm_, "val8"));
2429 
2430     int size = weakMap->GetSize(vm_);
2431     GTEST_LOG_(INFO) << "size : " << size;
2432     int32_t totalElements = weakMap->GetTotalElements(vm_);
2433     GTEST_LOG_(INFO) << "total elements : " << totalElements;
2434 
2435     for (int i = 0; i < size; ++i) {
2436         Local<JSValueRef> jsKey = weakMap->GetKey(vm_, i);
2437         Local<JSValueRef> jsVal = weakMap->GetValue(vm_, i);
2438         GTEST_LOG_(INFO) << "for WeakMap index : " << i << "    key : " << jsValue2String(vm_, jsKey) << "    val : " <<
2439             jsValue2String(vm_, jsVal);
2440     }
2441 
2442     bool hasKey2 = weakMap->Has(vm_, StringRef::NewFromUtf8(vm_, "key2"));
2443     GTEST_LOG_(INFO) << "Has Key2 : " << hasKey2;
2444     bool hasKey222 = weakMap->Has(vm_, StringRef::NewFromUtf8(vm_, "key222"));
2445     GTEST_LOG_(INFO) << "Has key222 : " << hasKey222;
2446 
2447     GTEST_LOG_(INFO) << "sample_demo9_map_test_2_WeakMapref =======================================";
2448 }
2449 
2450 /* demo10 set 的使用 */
HWTEST_F_L0(JSNApiSampleTest,sample_demo10_set)2451 HWTEST_F_L0(JSNApiSampleTest, sample_demo10_set)
2452 {
2453     GTEST_LOG_(INFO) << "sample_demo10_set =======================================";
2454     LocalScope scope(vm_);
2455     Local<SetRef> set = SetRef::New(vm_);
2456 
2457     set->Add(vm_, StringRef::NewFromUtf8(vm_, "val1"));
2458     int num2 = 222; // random number
2459     set->Add(vm_, NumberRef::New(vm_, num2));
2460     set->Add(vm_, BooleanRef::New(vm_, true));
2461     set->Add(vm_, SymbolRef::New(vm_, StringRef::NewFromUtf8(vm_, "val4")));
2462     set->Add(vm_, StringRef::NewFromUtf8(vm_, "val5"));
2463     int num6 = 666; // random number
2464     set->Add(vm_, IntegerRef::New(vm_, num6));
2465 
2466     int32_t size = set->GetSize(vm_);
2467     GTEST_LOG_(INFO) << "size : " << size;
2468     int32_t totalElement = set->GetTotalElements(vm_);
2469     GTEST_LOG_(INFO) << "total element : " << totalElement;
2470 
2471     for (int i = 0; i < size; ++i) {
2472         Local<JSValueRef> jsVal = set->GetValue(vm_, i);
2473         GTEST_LOG_(INFO) << "for set index : " << i << "    val : " << jsValue2String(vm_, jsVal);
2474     }
2475 
2476     // Iterator
2477     Local<SetIteratorRef> setIter = SetIteratorRef::New(vm_, set);
2478     ecmascript::EcmaRuntimeCallInfo *info = setIter->GetEcmaRuntimeCallInfo(vm_);
2479 
2480     Local<StringRef> kind = setIter->GetKind(vm_);
2481     GTEST_LOG_(INFO) << "Set Iterator kind : " << kind->ToString(vm_);
2482 
2483     for (Local<ArrayRef> array = SetIteratorRef::Next(vm_, info); array->IsArray(vm_);
2484         array = SetIteratorRef::Next(vm_, info)) {
2485         int index = setIter->GetIndex() - 1;
2486         Local<JSValueRef> jsVal = ArrayRef::GetValueAt(vm_, array, 1);
2487         GTEST_LOG_(INFO) << "for set iterator index : " << index << "    val : " << jsValue2String(vm_, jsVal);
2488     }
2489     GTEST_LOG_(INFO) << "sample_demo10_set =======================================";
2490 }
2491 
2492 /* demo10 WeakSet 的使用 */
HWTEST_F_L0(JSNApiSampleTest,sample_demo10_weakset)2493 HWTEST_F_L0(JSNApiSampleTest, sample_demo10_weakset)
2494 {
2495     GTEST_LOG_(INFO) << "sample_demo10_weakset =======================================";
2496     LocalScope scope(vm_);
2497     Local<WeakSetRef> weakSet = WeakSetRef::New(vm_);
2498 
2499     weakSet->Add(vm_, StringRef::NewFromUtf8(vm_, "val1"));
2500     int num2 = 666; // random number
2501     weakSet->Add(vm_, NumberRef::New(vm_, num2));
2502     weakSet->Add(vm_, BooleanRef::New(vm_, true));
2503     weakSet->Add(vm_, SymbolRef::New(vm_, StringRef::NewFromUtf8(vm_, "val4")));
2504     weakSet->Add(vm_, StringRef::NewFromUtf8(vm_, "val5"));
2505     int num6 = 666; // random number
2506     weakSet->Add(vm_, IntegerRef::New(vm_, num6));
2507 
2508     int32_t size = weakSet->GetSize(vm_);
2509     GTEST_LOG_(INFO) << "size : " << size;
2510     int32_t totalElement = weakSet->GetTotalElements(vm_);
2511     GTEST_LOG_(INFO) << "total element : " << totalElement;
2512 
2513     for (int i = 0; i < size; ++i) {
2514         Local<JSValueRef> jsVal = weakSet->GetValue(vm_, i);
2515         GTEST_LOG_(INFO) << "for weakset index : " << i << "    val : " << jsValue2String(vm_, jsVal);
2516     }
2517     GTEST_LOG_(INFO) << "sample_demo10_weakset =======================================";
2518 }
2519 
2520 // json对象获取值。
JsonObjGetValue(EcmaVM * vm,Local<ObjectRef> obj)2521 void JsonObjGetValue(EcmaVM *vm, Local<ObjectRef> obj)
2522 {
2523     Local<JSValueRef> jsVal1 = obj->Get(vm, StringRef::NewFromUtf8(vm, "str1"));
2524     bool jsVal1IsString = jsVal1->IsString(vm);
2525     Local<StringRef> val1 = jsVal1->ToString(vm);
2526     GTEST_LOG_(INFO) << "str1 : is string : " << jsVal1IsString << "  value : " << val1->ToString(vm);
2527     Local<JSValueRef> jsVal2 = obj->Get(vm, StringRef::NewFromUtf8(vm, "str2"));
2528     bool jsVal2IsNumber = jsVal2->IsNumber();
2529     int val2 = jsVal2->Int32Value(vm);
2530     GTEST_LOG_(INFO) << "str2 : is number : " << jsVal2IsNumber << "  value : " << val2;
2531     Local<JSValueRef> jsVal3 = obj->Get(vm, StringRef::NewFromUtf8(vm, "333"));
2532     int val3 = jsVal3->Int32Value(vm);
2533     GTEST_LOG_(INFO) << "333 : " << val3;
2534     Local<JSValueRef> jsVal4 = obj->Get(vm, StringRef::NewFromUtf8(vm, "444"));
2535     Local<StringRef> val4 = jsVal4->ToString(vm);
2536     GTEST_LOG_(INFO) << "str4 : " << val4->ToString(vm);
2537 
2538     Local<JSValueRef> jsVal8 = obj->Get(vm, StringRef::NewFromUtf8(vm, "b8"));
2539     bool jsVal8IsBool = jsVal8->IsBoolean();
2540     Local<BooleanRef> val8Ref = jsVal8;
2541     bool val8 = val8Ref->Value();
2542     GTEST_LOG_(INFO) << "b8  is bool : " << jsVal8IsBool << "    val : " << val8;
2543 }
2544 
2545 // json对象获取数组。
JsonObjGetArray(EcmaVM * vm,Local<ObjectRef> obj)2546 void JsonObjGetArray(EcmaVM *vm, Local<ObjectRef> obj)
2547 {
2548     Local<JSValueRef> jsVal5 = obj->Get(vm, StringRef::NewFromUtf8(vm, "arr5"));
2549     Local<ObjectRef> val5Obj = jsVal5;
2550     int length = val5Obj->Get(vm, StringRef::NewFromUtf8(vm, "length"))->Int32Value(vm);
2551     GTEST_LOG_(INFO) << "arr5 length : " << length;
2552     for (int i = 0; i < length; ++i) {
2553         Local<JSValueRef> val5Item = val5Obj->Get(vm, NumberRef::New(vm, i));
2554         GTEST_LOG_(INFO) << "arr5 : " << i << "    " << val5Item->Int32Value(vm);
2555     }
2556     Local<ArrayRef> val5Arr = jsVal5;
2557     uint32_t length2 = val5Arr->Length(vm);
2558     GTEST_LOG_(INFO) << "arr5 length2 : " << length2;
2559     for (uint32_t i = 0; i < length2; ++i) {
2560         Local<JSValueRef> val5Item = ArrayRef::GetValueAt(vm, val5Arr, i);
2561         GTEST_LOG_(INFO) << "arr5 : " << i << "    " << val5Item->Int32Value(vm);
2562     }
2563     Local<JSValueRef> jsVal6 = obj->Get(vm, StringRef::NewFromUtf8(vm, "arr6"));
2564     Local<ObjectRef> val6Obj = jsVal6;
2565     int length3 = val6Obj->Get(vm, StringRef::NewFromUtf8(vm, "length"))->Int32Value(vm);
2566     GTEST_LOG_(INFO) << "arr6 length : " << length3;
2567     for (int i = 0; i < length3; ++i) {
2568         Local<JSValueRef> val6Item = val6Obj->Get(vm, NumberRef::New(vm, i));
2569         GTEST_LOG_(INFO) << "arr6 : " << i << "    " << val6Item->ToString(vm)->ToString(vm);
2570     }
2571 }
2572 
2573 // json对象获取对象。
JsonObjGetObject(EcmaVM * vm,Local<ObjectRef> obj)2574 void JsonObjGetObject(EcmaVM *vm, Local<ObjectRef> obj)
2575 {
2576     Local<JSValueRef> jsVal7 = obj->Get(vm, StringRef::NewFromUtf8(vm, "data7"));
2577     Local<ObjectRef> val7Obj = jsVal7->ToObject(vm);
2578     Local<ArrayRef> val7ObjKeys = val7Obj->GetOwnPropertyNames(vm);
2579     for (uint32_t i = 0; i < val7ObjKeys->Length(vm); ++i) {
2580         Local<JSValueRef> itemKey = ArrayRef::GetValueAt(vm, val7ObjKeys, i);
2581         Local<JSValueRef> itemVal = val7Obj->Get(vm, itemKey);
2582         GTEST_LOG_(INFO) << "data7 :   item index:" << i << "    Key:" << itemKey->ToString(vm)->ToString(vm) <<
2583             "    val:" << itemVal->ToString(vm)->ToString(vm);
2584     }
2585 }
2586 
2587 /* demo11 json 测试,json字符串 转 obj。 注意key不能是纯数字。 json:
2588  * {
2589  * "str1": "val1",
2590  * "str2": 222,
2591  * "333": 456,
2592  * "444": "val4",
2593  * "arr5": [
2594  * 51,
2595  * 52,
2596  * 53,
2597  * 54,
2598  * 55
2599  * ],
2600  * "arr6": [
2601  * "str61",
2602  * "str62",
2603  * "str63",
2604  * "str64"
2605  * ],
2606  * "data7": {
2607  * "key71": "val71",
2608  * "key72": "val72"
2609  * },
2610  * "b8": true
2611  * }
2612  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo11_json_test_1_parse_object)2613 HWTEST_F_L0(JSNApiSampleTest, sample_demo11_json_test_1_parse_object)
2614 {
2615     GTEST_LOG_(INFO) << "sample_demo11_json_test_1_parse_object =======================================";
2616     LocalScope scope(vm_);
2617     std::string jsonStr =
2618         "{\"str1\":\"val1\",\"str2\":222,\"333\":456,\"444\":\"val4\",\"arr5\":[51,52,53,54,55],\"arr6\":[\"str61\","
2619         "\"str62\",\"str63\",\"str64\"],\"data7\":{\"key71\":\"val71\",\"key72\":\"val72\"},\"b8\":true}";
2620     Local<JSValueRef> jsObj = JSON::Parse(vm_, StringRef::NewFromUtf8(vm_, jsonStr.c_str()));
2621     Local<ObjectRef> obj = jsObj->ToObject(vm_);
2622 
2623     JsonObjGetValue(vm_, obj);
2624     JsonObjGetArray(vm_, obj);
2625     JsonObjGetObject(vm_, obj);
2626 
2627     GTEST_LOG_(INFO) << "sample_demo11_json_test_1_parse_object =======================================";
2628 }
2629 
2630 /* demo11 json 测试,obj转json字符串。 json:
2631  * {
2632  * "key1": "val1",
2633  * "key2": 123,
2634  * "333": "val3",
2635  * "arr4": [
2636  * "val40",
2637  * "val41",
2638  * "val42",
2639  * "val43"
2640  * ],
2641  * "arr5": [
2642  * 50,
2643  * 51,
2644  * 52,
2645  * 53
2646  * ],
2647  * "b6": true,
2648  * "obj7": {
2649  * "key71": "val71",
2650  * "key72": "val72",
2651  * "key73": "val73"
2652  * }
2653  * }
2654  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo11_json_test_2_stringify_object)2655 HWTEST_F_L0(JSNApiSampleTest, sample_demo11_json_test_2_stringify_object)
2656 {
2657     GTEST_LOG_(INFO) << "sample_demo11_json_test_2_stringify_object =======================================";
2658     LocalScope scope(vm_);
2659 
2660     Local<ObjectRef> obj = ObjectRef::New(vm_);
2661     obj->Set(vm_, StringRef::NewFromUtf8(vm_, "key1"), StringRef::NewFromUtf8(vm_, "val1"));
2662     int num2 = 123; // random number
2663     obj->Set(vm_, StringRef::NewFromUtf8(vm_, "key2"), NumberRef::New(vm_, num2));
2664     int num3 = 333; // random number
2665     obj->Set(vm_, NumberRef::New(vm_, num3), StringRef::NewFromUtf8(vm_, "val3"));
2666 
2667     Local<ArrayRef> arr4 = ArrayRef::New(vm_);
2668     ArrayRef::SetValueAt(vm_, arr4, 0, StringRef::NewFromUtf8(vm_, "val40"));
2669     ArrayRef::SetValueAt(vm_, arr4, 1, StringRef::NewFromUtf8(vm_, "val41"));
2670     ArrayRef::SetValueAt(vm_, arr4, 2, StringRef::NewFromUtf8(vm_, "val42"));
2671     ArrayRef::SetValueAt(vm_, arr4, 3, StringRef::NewFromUtf8(vm_, "val43"));
2672     obj->Set(vm_, StringRef::NewFromUtf8(vm_, "arr4"), arr4);
2673 
2674     Local<ArrayRef> arr5 = ArrayRef::New(vm_);
2675     int num50 = 50; // random number
2676     int num51 = 51; // random number
2677     int num52 = 52; // random number
2678     int num53 = 53; // random number
2679     ArrayRef::SetValueAt(vm_, arr5, 0, IntegerRef::New(vm_, num50));
2680     ArrayRef::SetValueAt(vm_, arr5, 1, IntegerRef::New(vm_, num51));
2681     ArrayRef::SetValueAt(vm_, arr5, 2, IntegerRef::New(vm_, num52));
2682     ArrayRef::SetValueAt(vm_, arr5, 3, IntegerRef::New(vm_, num53));
2683     obj->Set(vm_, StringRef::NewFromUtf8(vm_, "arr5"), arr5);
2684 
2685     obj->Set(vm_, StringRef::NewFromUtf8(vm_, "b6"), BooleanRef::New(vm_, true));
2686 
2687     Local<ObjectRef> obj7 = ObjectRef::New(vm_);
2688     obj7->Set(vm_, StringRef::NewFromUtf8(vm_, "key71"), StringRef::NewFromUtf8(vm_, "val71"));
2689     obj7->Set(vm_, StringRef::NewFromUtf8(vm_, "key72"), StringRef::NewFromUtf8(vm_, "val72"));
2690     obj7->Set(vm_, StringRef::NewFromUtf8(vm_, "key73"), StringRef::NewFromUtf8(vm_, "val73"));
2691 
2692     obj->Set(vm_, StringRef::NewFromUtf8(vm_, "obj7"), obj7);
2693 
2694     Local<JSValueRef> jsStr = JSON::Stringify(vm_, obj);
2695     GTEST_LOG_(INFO) << "jsStr is String : " << jsStr->IsString(vm_);
2696     Local<StringRef> strRef = jsStr->ToString(vm_);
2697     std::string str = strRef->ToString(vm_);
2698     GTEST_LOG_(INFO) << "json : " << str;
2699 
2700     GTEST_LOG_(INFO) << "sample_demo11_json_test_2_stringify_object =======================================";
2701 }
2702 
2703 /* demo11 json 测试,json字符串转为数组。 json:
2704  * [51,52,53,54,55]
2705  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo11_json_test_3_parse_array1)2706 HWTEST_F_L0(JSNApiSampleTest, sample_demo11_json_test_3_parse_array1)
2707 {
2708     GTEST_LOG_(INFO) << "sample_demo11_json_test_3_parse_array1 =======================================";
2709     LocalScope scope(vm_);
2710 
2711     // 随机的一个 json 数字 数组。  [51,52,53,54,55]
2712     Local<StringRef> arrStr1 = StringRef::NewFromUtf8(vm_, "[51,52,53,54,55]");
2713     Local<JSValueRef> jsArr1 = JSON::Parse(vm_, arrStr1);
2714     bool jsArr1IsArr = jsArr1->IsArray(vm_);
2715     GTEST_LOG_(INFO) << "jsArr1 is array : " << jsArr1IsArr;
2716     Local<ArrayRef> arr1 = jsArr1;
2717     uint32_t arr1Length = arr1->Length(vm_);
2718     GTEST_LOG_(INFO) << "arr1 length : " << arr1Length;
2719     for (uint32_t i = 0; i < arr1Length; ++i) {
2720         Local<JSValueRef> arr1Item = ArrayRef::GetValueAt(vm_, arr1, i);
2721         if (arr1Item->IsNumber()) {
2722             int num = arr1Item->Int32Value(vm_);
2723             GTEST_LOG_(INFO) << "arr1 index : " << i << "  value : " << num;
2724         } else {
2725             GTEST_LOG_(INFO) << "arr1 index : " << i << "  not number !";
2726         }
2727     }
2728     GTEST_LOG_(INFO) << "sample_demo11_json_test_3_parse_array1 =======================================";
2729 }
2730 
2731 /* demo11 json 测试,json字符串转为数组。 json:
2732  * ["a1","a2","a3","a4","a5","a6"]
2733  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo11_json_test_3_parse_array2)2734 HWTEST_F_L0(JSNApiSampleTest, sample_demo11_json_test_3_parse_array2)
2735 {
2736     GTEST_LOG_(INFO) << "sample_demo11_json_test_3_parse_array2 =======================================";
2737     LocalScope scope(vm_);
2738 
2739     // 随机的一个json字符串数组。 ["a1","a2","a3","a4","a5","a6"]
2740     Local<StringRef> arrStr2 = StringRef::NewFromUtf8(vm_, "[\"a1\",\"a2\",\"a3\",\"a4\",\"a5\",\"a6\"]");
2741     Local<JSValueRef> jsArr2 = JSON::Parse(vm_, arrStr2);
2742     bool jsArr2IsArr = jsArr2->IsArray(vm_);
2743     GTEST_LOG_(INFO) << "jsArr2 is array : " << jsArr2IsArr;
2744     Local<ArrayRef> arr2 = jsArr2;
2745     uint32_t arr2Length = arr2->Length(vm_);
2746     GTEST_LOG_(INFO) << "arr2 length : " << arr2Length;
2747     for (uint32_t i = 0; i < arr2Length; ++i) {
2748         Local<JSValueRef> arr2Item = ArrayRef::GetValueAt(vm_, arr2, i);
2749         std::string str = arr2Item->ToString(vm_)->ToString(vm_);
2750         GTEST_LOG_(INFO) << "arr2 index : " << i << "  value : " << str;
2751     }
2752 
2753     GTEST_LOG_(INFO) << "sample_demo11_json_test_3_parse_array2 =======================================";
2754 }
2755 
2756 /* demo11 json 测试,json字符串转为数组。 json:
2757  * [true,true,false,false,true]
2758  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo11_json_test_3_parse_array3)2759 HWTEST_F_L0(JSNApiSampleTest, sample_demo11_json_test_3_parse_array3)
2760 {
2761     GTEST_LOG_(INFO) << "sample_demo11_json_test_3_parse_array3 =======================================";
2762     LocalScope scope(vm_);
2763     Local<StringRef> arrStr3 = StringRef::NewFromUtf8(vm_, "[true,true,false,false,true]");
2764     Local<JSValueRef> jsArr3 = JSON::Parse(vm_, arrStr3);
2765     bool jsArr3IsArr = jsArr3->IsArray(vm_);
2766     GTEST_LOG_(INFO) << "jsArr3 is array : " << jsArr3IsArr;
2767     Local<ArrayRef> arr3 = jsArr3;
2768     uint32_t arr3Length = arr3->Length(vm_);
2769     GTEST_LOG_(INFO) << "arr3 length : " << arr3Length;
2770     for (uint32_t i = 0; i < arr3Length; ++i) {
2771         Local<JSValueRef> arr3Item = ArrayRef::GetValueAt(vm_, arr3, i);
2772         int b = arr3Item->BooleaValue(vm_);
2773         GTEST_LOG_(INFO) << "arr3 index : " << i << "  value : " << b;
2774     }
2775     GTEST_LOG_(INFO) << "sample_demo11_json_test_3_parse_array3 =======================================";
2776 }
2777 
2778 /* demo11 json 测试,json字符串转为数组。 json:
2779  * [
2780  * {
2781  * "key1": "val11",
2782  * "key2": "val12"
2783  * },
2784  * {
2785  * "key1": "val21",
2786  * "key2": "val22"
2787  * },
2788  * {
2789  * "key1": "val31",
2790  * "key2": "val32"
2791  * }
2792  * ]
2793  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo11_json_test_3_parse_array4)2794 HWTEST_F_L0(JSNApiSampleTest, sample_demo11_json_test_3_parse_array4)
2795 {
2796     GTEST_LOG_(INFO) << "sample_demo11_json_test_3_parse_array4 =======================================";
2797     LocalScope scope(vm_);
2798 
2799     // json 对象数组。
2800     // json: [{"key1": "val11","key2": "val12"},{"key1": "val21","key2": "val22"},{"key1": "val31","key2": "val32"}]
2801     Local<StringRef> arrStr4 =
2802         StringRef::NewFromUtf8(vm_, "[{\"key1\":\"val11\",\"key2\":\"val12\"},{\"key1\":\"val21\",\"key2\":\"val22\"},{"
2803         "\"key1\":\"val31\",\"key2\":\"val32\"}]");
2804     Local<JSValueRef> jsArr4 = JSON::Parse(vm_, arrStr4);
2805     bool jsArr4IsArr = jsArr4->IsArray(vm_);
2806     GTEST_LOG_(INFO) << "jsArr4 is array : " << jsArr4IsArr;
2807     Local<ArrayRef> arr4 = jsArr4;
2808     uint32_t arr4Length = arr4->Length(vm_);
2809     GTEST_LOG_(INFO) << "arr4 length : " << arr4Length;
2810     for (uint32_t i = 0; i < arr4Length; ++i) {
2811         Local<JSValueRef> jsArr4Item = ArrayRef::GetValueAt(vm_, arr4, i);
2812         Local<ObjectRef> obj = jsArr4Item->ToObject(vm_);
2813 
2814         Local<JSValueRef> objVal1 = obj->Get(vm_, StringRef::NewFromUtf8(vm_, "key1"));
2815         Local<JSValueRef> objVal2 = obj->Get(vm_, StringRef::NewFromUtf8(vm_, "key2"));
2816 
2817         GTEST_LOG_(INFO) << "arr4 index : " << i << "  key1 : " << objVal1->ToString(vm_)->ToString(vm_);
2818         GTEST_LOG_(INFO) << "arr4 index : " << i << "  key2 : " << objVal2->ToString(vm_)->ToString(vm_);
2819     }
2820 
2821     GTEST_LOG_(INFO) << "sample_demo11_json_test_3_parse_array4 =======================================";
2822 }
2823 
2824 /* demo11 json 测试,json字符串转为数组。 json:
2825  * ["val1",222,true,{"key1": "val1","key2": "val2"}]
2826  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo11_json_test_3_parse_array5)2827 HWTEST_F_L0(JSNApiSampleTest, sample_demo11_json_test_3_parse_array5)
2828 {
2829     GTEST_LOG_(INFO) << "sample_demo11_json_test_3_parse_array5 =======================================";
2830     LocalScope scope(vm_);
2831 
2832     // json 数组: ["val1",222,true,{"key1": "val1","key2": "val2"}]
2833     Local<StringRef> arrStr5 = StringRef::NewFromUtf8(vm_, "[\"val1\",222,true,{\"key1\":\"val1\",\"key2\":\"val1\"}]");
2834     Local<JSValueRef> jsArr5 = JSON::Parse(vm_, arrStr5);
2835     bool jsArr5IsArr = jsArr5->IsArray(vm_);
2836     GTEST_LOG_(INFO) << "jsArr5 is array : " << jsArr5IsArr;
2837     Local<ArrayRef> arr5 = jsArr5;
2838     uint32_t arr5Length = arr5->Length(vm_);
2839     GTEST_LOG_(INFO) << "arr5 length : " << arr5Length;
2840     for (uint32_t i = 0; i < arr5Length; ++i) {
2841         Local<JSValueRef> arr5Item = ArrayRef::GetValueAt(vm_, arr5, i);
2842         if (arr5Item->IsString(vm_)) {
2843             GTEST_LOG_(INFO) << "arr5 index : " << i << "  value : " << arr5Item->ToString(vm_)->ToString(vm_);
2844         } else if (arr5Item->IsNumber()) {
2845             GTEST_LOG_(INFO) << "arr5 index : " << i << "  value : " << arr5Item->Int32Value(vm_);
2846         } else if (arr5Item->IsBoolean()) {
2847             GTEST_LOG_(INFO) << "arr5 index : " << i << "  value : " << arr5Item->ToBoolean(vm_)->Value();
2848         } else if (arr5Item->IsObject(vm_)) {
2849             Local<ObjectRef> obj = arr5Item->ToObject(vm_);
2850             Local<ObjectRef> val1 = obj->Get(vm_, StringRef::NewFromUtf8(vm_, "key1"));
2851             Local<ObjectRef> val2 = obj->Get(vm_, StringRef::NewFromUtf8(vm_, "key2"));
2852             GTEST_LOG_(INFO) << "arr5 index : " << i << "  key1 : " << val1->ToString(vm_)->ToString(vm_);
2853             GTEST_LOG_(INFO) << "arr5 index : " << i << "  key2 : " << val2->ToString(vm_)->ToString(vm_);
2854         } else {
2855             GTEST_LOG_(INFO) << "arr5 index : " << i << "  not type !";
2856         }
2857     }
2858     GTEST_LOG_(INFO) << "sample_demo11_json_test_3_parse_array5 =======================================";
2859 }
2860 
2861 /* demo11 json 测试,数组转json字符串。 json:
2862  * ["val0","val1","val2","val3"]
2863  * [
2864  * {
2865  * "key1": "val11",
2866  * "key2": "val12",
2867  * "key3": "val13"
2868  * },
2869  * {
2870  * "key1": "val21",
2871  * "key2": "val22",
2872  * "key3": "val23"
2873  * }
2874  * ]
2875  * [
2876  * "val1",
2877  * 222,
2878  * true,
2879  * {
2880  * "key1": "val1",
2881  * "key2": "val2"
2882  * }
2883  * ]
2884  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo11_json_test_4_stringify_array1)2885 HWTEST_F_L0(JSNApiSampleTest, sample_demo11_json_test_4_stringify_array1)
2886 {
2887     GTEST_LOG_(INFO) << "sample_demo11_json_test_4_stringify_array1 =======================================";
2888     LocalScope scope(vm_);
2889     Local<ArrayRef> arr = ArrayRef::New(vm_);
2890     ArrayRef::SetValueAt(vm_, arr, 0, StringRef::NewFromUtf8(vm_, "val0"));
2891     ArrayRef::SetValueAt(vm_, arr, 1, StringRef::NewFromUtf8(vm_, "val1"));
2892     ArrayRef::SetValueAt(vm_, arr, 2, StringRef::NewFromUtf8(vm_, "val2"));
2893     ArrayRef::SetValueAt(vm_, arr, 3, StringRef::NewFromUtf8(vm_, "val3"));
2894     Local<JSValueRef> json1 = JSON::Stringify(vm_, arr);
2895     GTEST_LOG_(INFO) << " js arr 1 json : " << json1->ToString(vm_)->ToString(vm_);
2896     GTEST_LOG_(INFO) << "sample_demo11_json_test_4_stringify_array1 =======================================";
2897 }
2898 
HWTEST_F_L0(JSNApiSampleTest,sample_demo11_json_test_4_stringify_array2)2899 HWTEST_F_L0(JSNApiSampleTest, sample_demo11_json_test_4_stringify_array2)
2900 {
2901     GTEST_LOG_(INFO) << "sample_demo11_json_test_4_stringify_array2 =======================================";
2902     Local<ObjectRef> obj1 = ObjectRef::New(vm_);
2903     obj1->Set(vm_, StringRef::NewFromUtf8(vm_, "key1"), StringRef::NewFromUtf8(vm_, "val11"));
2904     obj1->Set(vm_, StringRef::NewFromUtf8(vm_, "key2"), StringRef::NewFromUtf8(vm_, "val12"));
2905     obj1->Set(vm_, StringRef::NewFromUtf8(vm_, "key3"), StringRef::NewFromUtf8(vm_, "val13"));
2906     Local<ObjectRef> obj2 = ObjectRef::New(vm_);
2907     obj2->Set(vm_, StringRef::NewFromUtf8(vm_, "key1"), StringRef::NewFromUtf8(vm_, "val21"));
2908     obj2->Set(vm_, StringRef::NewFromUtf8(vm_, "key2"), StringRef::NewFromUtf8(vm_, "val22"));
2909     obj2->Set(vm_, StringRef::NewFromUtf8(vm_, "key3"), StringRef::NewFromUtf8(vm_, "val23"));
2910     Local<ArrayRef> arr = ArrayRef::New(vm_);
2911     ArrayRef::SetValueAt(vm_, arr, 0, obj1);
2912     ArrayRef::SetValueAt(vm_, arr, 1, obj2);
2913     Local<JSValueRef> json2 = JSON::Stringify(vm_, arr);
2914     GTEST_LOG_(INFO) << " js arr 2 json : " << json2->ToString(vm_)->ToString(vm_);
2915     GTEST_LOG_(INFO) << "sample_demo11_json_test_4_stringify_array2 =======================================";
2916 }
2917 
HWTEST_F_L0(JSNApiSampleTest,sample_demo11_json_test_4_stringify_array3)2918 HWTEST_F_L0(JSNApiSampleTest, sample_demo11_json_test_4_stringify_array3)
2919 {
2920     GTEST_LOG_(INFO) << "sample_demo11_json_test_4_stringify_array3 =======================================";
2921     Local<ObjectRef> obj = ObjectRef::New(vm_);
2922     obj->Set(vm_, StringRef::NewFromUtf8(vm_, "key1"), StringRef::NewFromUtf8(vm_, "val1"));
2923     obj->Set(vm_, StringRef::NewFromUtf8(vm_, "key2"), StringRef::NewFromUtf8(vm_, "val2"));
2924     Local<ArrayRef> arr = ArrayRef::New(vm_);
2925     ArrayRef::SetValueAt(vm_, arr, 0, StringRef::NewFromUtf8(vm_, "val1"));
2926     int num2 = 222; // random number
2927     ArrayRef::SetValueAt(vm_, arr, 1, NumberRef::New(vm_, num2));
2928     ArrayRef::SetValueAt(vm_, arr, 2, BooleanRef::New(vm_, true));
2929     ArrayRef::SetValueAt(vm_, arr, 3, obj);
2930     Local<JSValueRef> json3 = JSON::Stringify(vm_, arr);
2931     GTEST_LOG_(INFO) << " js arr 3 json : " << json3->ToString(vm_)->ToString(vm_);
2932     GTEST_LOG_(INFO) << "sample_demo11_json_test_4_stringify_array3 =======================================";
2933 }
2934 
2935 /* demo12 异常的抛出和处理 */
2936 // 抛出异常的测试函数
ThrowErrorFuncTest(const EcmaVM * vm,Local<NumberRef> par)2937 Local<JSValueRef> ThrowErrorFuncTest(const EcmaVM *vm, Local<NumberRef> par)
2938 {
2939     int i = par->Int32Value(vm);
2940     if (i == 0) {
2941         std::string errStr = std::string("function:").append(__func__).append("err:Error");
2942         Local<JSValueRef> error = Exception::Error(vm, StringRef::NewFromUtf8(vm, errStr.c_str()));
2943         JSNApi::ThrowException(vm, error);
2944         return JSValueRef::Undefined(vm);
2945     }
2946     int num = 2; // 函数的功能,原数字的2倍。
2947     return NumberRef::New(vm, i * num);
2948 }
2949 
ThrowRangeErrorFuncTest(const EcmaVM * vm,Local<NumberRef> par)2950 Local<JSValueRef> ThrowRangeErrorFuncTest(const EcmaVM *vm, Local<NumberRef> par)
2951 {
2952     int i = par->Int32Value(vm);
2953     if (i == 0) {
2954         std::string errStr = std::string("function:").append(__func__).append("err:RangeError");
2955         Local<JSValueRef> error = Exception::RangeError(vm, StringRef::NewFromUtf8(vm, errStr.c_str()));
2956         JSNApi::ThrowException(vm, error);
2957         return JSValueRef::Undefined(vm);
2958     }
2959     int num = 2; // 函数的功能,原数字的2倍。
2960     return NumberRef::New(vm, i * num);
2961 }
2962 
ThrowReferenceErrorFuncTest(const EcmaVM * vm,Local<NumberRef> par)2963 Local<JSValueRef> ThrowReferenceErrorFuncTest(const EcmaVM *vm, Local<NumberRef> par)
2964 {
2965     int i = par->Int32Value(vm);
2966     if (i == 0) {
2967         std::string errStr = std::string("function:").append(__func__).append("err:ReferenceError");
2968         Local<JSValueRef> error = Exception::ReferenceError(vm, StringRef::NewFromUtf8(vm, errStr.c_str()));
2969         JSNApi::ThrowException(vm, error);
2970         return JSValueRef::Undefined(vm);
2971     }
2972     int num = 2; // 函数的功能,原数字的2倍。
2973     return NumberRef::New(vm, i * num);
2974 }
2975 
ThrowSyntaxErrorFuncTest(const EcmaVM * vm,Local<NumberRef> par)2976 Local<JSValueRef> ThrowSyntaxErrorFuncTest(const EcmaVM *vm, Local<NumberRef> par)
2977 {
2978     int i = par->Int32Value(vm);
2979     if (i == 0) {
2980         std::string errStr = std::string("function:").append(__func__).append("err:SyntaxError");
2981         Local<JSValueRef> error = Exception::SyntaxError(vm, StringRef::NewFromUtf8(vm, errStr.c_str()));
2982         JSNApi::ThrowException(vm, error);
2983         return JSValueRef::Undefined(vm);
2984     }
2985     int num = 2; // 函数的功能,原数字的2倍。
2986     return NumberRef::New(vm, i * num);
2987 }
2988 
ThrowTypeErrorFuncTest(const EcmaVM * vm,Local<NumberRef> par)2989 Local<JSValueRef> ThrowTypeErrorFuncTest(const EcmaVM *vm, Local<NumberRef> par)
2990 {
2991     int i = par->Int32Value(vm);
2992     if (i == 0) {
2993         std::string errStr = std::string("function:").append(__func__).append("err:TypeError");
2994         Local<JSValueRef> error = Exception::TypeError(vm, StringRef::NewFromUtf8(vm, errStr.c_str()));
2995         JSNApi::ThrowException(vm, error);
2996         return JSValueRef::Undefined(vm);
2997     }
2998     int num = 2; // 函数的功能,原数字的2倍。
2999     return NumberRef::New(vm, i * num);
3000 }
3001 
ThrowAggregateErrorFuncTest(const EcmaVM * vm,Local<NumberRef> par)3002 Local<JSValueRef> ThrowAggregateErrorFuncTest(const EcmaVM *vm, Local<NumberRef> par)
3003 {
3004     int i = par->Int32Value(vm);
3005     if (i == 0) {
3006         std::string errStr = std::string("function:").append(__func__).append("err:AggregateError");
3007         Local<JSValueRef> error = Exception::AggregateError(vm, StringRef::NewFromUtf8(vm, errStr.c_str()));
3008         JSNApi::ThrowException(vm, error);
3009         return JSValueRef::Undefined(vm);
3010     }
3011     int num = 2; // 函数的功能,原数字的2倍。
3012     return NumberRef::New(vm, i * num);
3013 }
3014 
ThrowEvalErrorFuncTest(const EcmaVM * vm,Local<NumberRef> par)3015 Local<JSValueRef> ThrowEvalErrorFuncTest(const EcmaVM *vm, Local<NumberRef> par)
3016 {
3017     int i = par->Int32Value(vm);
3018     if (i == 0) {
3019         std::string errStr = std::string("function:").append(__func__).append("err:EvalError");
3020         Local<JSValueRef> error = Exception::EvalError(vm, StringRef::NewFromUtf8(vm, errStr.c_str()));
3021         JSNApi::ThrowException(vm, error);
3022         return JSValueRef::Undefined(vm);
3023     }
3024     int num = 2; // 函数的功能,原数字的2倍。
3025     return NumberRef::New(vm, i * num);
3026 }
3027 
ThrowOOMErrorFuncTest(const EcmaVM * vm,Local<NumberRef> par)3028 Local<JSValueRef> ThrowOOMErrorFuncTest(const EcmaVM *vm, Local<NumberRef> par)
3029 {
3030     int i = par->Int32Value(vm);
3031     if (i == 0) {
3032         std::string errStr = std::string("function:").append(__func__).append("err:OOMError");
3033         Local<JSValueRef> error = Exception::OOMError(vm, StringRef::NewFromUtf8(vm, errStr.c_str()));
3034         JSNApi::ThrowException(vm, error);
3035         return JSValueRef::Undefined(vm);
3036     }
3037     int num = 2; // 函数的功能,原数字的2倍。
3038     return NumberRef::New(vm, i * num);
3039 }
3040 
ThrowTerminationErrorFuncTest(const EcmaVM * vm,Local<NumberRef> par)3041 Local<JSValueRef> ThrowTerminationErrorFuncTest(const EcmaVM *vm, Local<NumberRef> par)
3042 {
3043     int i = par->Int32Value(vm);
3044     if (i == 0) {
3045         std::string errStr = std::string("function:").append(__func__).append("err:TerminationError");
3046         Local<JSValueRef> error = Exception::TerminationError(vm, StringRef::NewFromUtf8(vm, errStr.c_str()));
3047         JSNApi::ThrowException(vm, error);
3048         return JSValueRef::Undefined(vm);
3049     }
3050     int num = 2; // 函数的功能,原数字的2倍。
3051     return NumberRef::New(vm, i * num);
3052 }
3053 
3054 // 处理异常,用 JSNApi 类中的函数。
ClearAndPrintException4JSNApi(const EcmaVM * vm,const std::string log)3055 void ClearAndPrintException4JSNApi(const EcmaVM *vm, const std::string log)
3056 {
3057     if (!JSNApi::HasPendingException(vm)) {
3058         GTEST_LOG_(INFO) << log << " no exception .";
3059         return;
3060     }
3061 
3062     JSNApi::PrintExceptionInfo(vm);
3063     Local<ObjectRef> exception = JSNApi::GetAndClearUncaughtException(vm);
3064     std::string exceptionName = exception->Get(vm, StringRef::NewFromUtf8(vm, "name"))->ToString(vm)->ToString(vm);
3065     std::string exceptionMessage = exception->Get(vm, StringRef::NewFromUtf8(vm,
3066         "message"))->ToString(vm)->ToString(vm);
3067     std::string exceptionStack = exception->Get(vm,
3068         StringRef::NewFromUtf8(vm, "stack"))->ToString(vm)->ToString(vm);
3069 
3070     GTEST_LOG_(INFO) << log << " exception name : " << exceptionName;
3071     GTEST_LOG_(INFO) << log << " exception message : " << exceptionMessage;
3072     GTEST_LOG_(INFO) << log << " exception stack : " << exceptionStack;
3073 };
3074 
3075 // 处理异常,用 TryCatch 类中的函数。
ClearAndPrintException4TryCatch1(const EcmaVM * vm,const std::string log)3076 void ClearAndPrintException4TryCatch1(const EcmaVM *vm, const std::string log)
3077 {
3078     TryCatch tryCatch(vm);
3079     if (!tryCatch.HasCaught()) {
3080         GTEST_LOG_(INFO) << log << " no exception .";
3081         return;
3082     }
3083     Local<ObjectRef> exception = tryCatch.GetAndClearException();
3084     std::string exceptionName = exception->Get(vm, StringRef::NewFromUtf8(vm, "name"))->ToString(vm)->ToString(vm);
3085     std::string exceptionMessage = exception->Get(vm,
3086         StringRef::NewFromUtf8(vm, "message"))->ToString(vm)->ToString(vm);
3087     std::string exceptionStack = exception->Get(vm, StringRef::NewFromUtf8(vm, "stack"))->ToString(vm)->ToString(vm);
3088 
3089     GTEST_LOG_(INFO) << log << " exception name : " << exceptionName;
3090     GTEST_LOG_(INFO) << log << " exception message : " << exceptionMessage;
3091     GTEST_LOG_(INFO) << log << " exception stack : " << exceptionStack;
3092 };
3093 
3094 // 处理异常,用 TryCatch 类中的函数。
ClearAndPrintException4TryCatch2(const EcmaVM * vm,const std::string log)3095 void ClearAndPrintException4TryCatch2(const EcmaVM *vm, const std::string log)
3096 {
3097     TryCatch tryCatch(vm);
3098     if (!tryCatch.HasCaught()) {
3099         GTEST_LOG_(INFO) << log << " no exception .";
3100         return;
3101     }
3102 
3103     Local<ObjectRef> exception = tryCatch.GetException();
3104     tryCatch.ClearException();
3105     std::string exceptionName = exception->Get(vm, StringRef::NewFromUtf8(vm, "name"))->ToString(vm)->ToString(vm);
3106     std::string exceptionMessage = exception->Get(vm,
3107         StringRef::NewFromUtf8(vm, "message"))->ToString(vm)->ToString(vm);
3108     std::string exceptionStack = exception->Get(vm, StringRef::NewFromUtf8(vm, "stack"))->ToString(vm)->ToString(vm);
3109 
3110     GTEST_LOG_(INFO) << log << " exception name : " << exceptionName;
3111     GTEST_LOG_(INFO) << log << " exception message : " << exceptionMessage;
3112     GTEST_LOG_(INFO) << log << " exception stack : " << exceptionStack;
3113     tryCatch.Rethrow();
3114 };
3115 
3116 // 异常没有处理重新抛出异常,用 TryCatch 类中的函数。
PrintAndRethrowException4TryCatch3(const EcmaVM * vm,const std::string log)3117 void PrintAndRethrowException4TryCatch3(const EcmaVM *vm, const std::string log)
3118 {
3119     TryCatch tryCatch(vm);
3120     if (!tryCatch.HasCaught()) {
3121         GTEST_LOG_(INFO) << log << " no exception .";
3122         return;
3123     }
3124 
3125     Local<ObjectRef> exception = tryCatch.GetAndClearException();
3126     std::string exceptionName = exception->Get(vm, StringRef::NewFromUtf8(vm, "name"))->ToString(vm)->ToString(vm);
3127     std::string exceptionMessage = exception->Get(vm,
3128         StringRef::NewFromUtf8(vm, "message"))->ToString(vm)->ToString(vm);
3129     std::string exceptionStack = exception->Get(vm, StringRef::NewFromUtf8(vm, "stack"))->ToString(vm)->ToString(vm);
3130 
3131     GTEST_LOG_(INFO) << log << " exception name : " << exceptionName;
3132     GTEST_LOG_(INFO) << log << " exception message : " << exceptionMessage;
3133     GTEST_LOG_(INFO) << log << " exception stack : " << exceptionStack;
3134     tryCatch.Rethrow();
3135 };
3136 
3137 /* demo12 异常的抛出和处理 */
HWTEST_F_L0(JSNApiSampleTest,sample_demo12_exception_test)3138 HWTEST_F_L0(JSNApiSampleTest, sample_demo12_exception_test)
3139 {
3140     GTEST_LOG_(INFO) << "sample_demo12_exception_test =======================================";
3141     LocalScope scope(vm_);
3142     // Error
3143     Local<JSValueRef> exception1 = ThrowErrorFuncTest(vm_, NumberRef::New(vm_, 0));
3144     if (exception1->IsUndefined()) {
3145         ClearAndPrintException4JSNApi(vm_, "ThrowErrorFuncTest");
3146     }
3147     // RangeError
3148     Local<JSValueRef> exception2 = ThrowRangeErrorFuncTest(vm_, NumberRef::New(vm_, 0));
3149     if (exception2->IsUndefined()) {
3150         ClearAndPrintException4TryCatch1(vm_, "ThrowRangeErrorFuncTest");
3151     }
3152     // ReferenceError
3153     Local<JSValueRef> exception3 = ThrowReferenceErrorFuncTest(vm_, NumberRef::New(vm_, 0));
3154     if (exception3->IsUndefined()) {
3155         ClearAndPrintException4TryCatch2(vm_, "ThrowReferenceErrorFuncTest");
3156     }
3157     // SyntaxError
3158     Local<JSValueRef> exception4 = ThrowSyntaxErrorFuncTest(vm_, NumberRef::New(vm_, 0));
3159     if (exception4->IsUndefined()) {
3160         PrintAndRethrowException4TryCatch3(vm_, "ThrowSyntaxErrorFuncTest");
3161         ClearAndPrintException4TryCatch1(vm_, "ThrowSyntaxErrorFuncTest");
3162     }
3163     // TypeError
3164     Local<JSValueRef> exception5 = ThrowTypeErrorFuncTest(vm_, NumberRef::New(vm_, 0));
3165     if (exception5->IsUndefined()) {
3166         ClearAndPrintException4TryCatch1(vm_, "ThrowTypeErrorFuncTest");
3167     }
3168     // AggregateError
3169     Local<JSValueRef> exception6 = ThrowAggregateErrorFuncTest(vm_, NumberRef::New(vm_, 0));
3170     if (exception6->IsUndefined()) {
3171         ClearAndPrintException4TryCatch1(vm_, "ThrowAggregateErrorFuncTest");
3172     }
3173     // EvalError
3174     Local<JSValueRef> exception7 = ThrowEvalErrorFuncTest(vm_, NumberRef::New(vm_, 0));
3175     if (exception7->IsUndefined()) {
3176         ClearAndPrintException4TryCatch1(vm_, "ThrowEvalErrorFuncTest");
3177     }
3178     // OOMError
3179     Local<JSValueRef> exception8 = ThrowOOMErrorFuncTest(vm_, NumberRef::New(vm_, 0));
3180     if (exception8->IsUndefined()) {
3181         ClearAndPrintException4TryCatch1(vm_, "ThrowOOMErrorFuncTest");
3182     }
3183     // TerminationError
3184     Local<JSValueRef> exception9 = ThrowTerminationErrorFuncTest(vm_, NumberRef::New(vm_, 0));
3185     if (exception9->IsUndefined()) {
3186         ClearAndPrintException4TryCatch1(vm_, "ThrowTerminationErrorFuncTest");
3187     }
3188     GTEST_LOG_(INFO) << "sample_demo12_exception_test =======================================";
3189 }
3190 }