1 /*
2 * Copyright (c) 2021 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
18 #include "ecmascript/builtins/builtins_function.h"
19 #include "ecmascript/builtins/builtins.h"
20 #include "ecmascript/ecma_global_storage.h"
21 #include "ecmascript/ecma_vm.h"
22 #include "ecmascript/global_env.h"
23 #include "ecmascript/js_bigint.h"
24 #include "ecmascript/js_runtime_options.h"
25 #include "ecmascript/js_thread.h"
26 #include "ecmascript/napi/include/jsnapi.h"
27 #include "ecmascript/napi/jsnapi_helper.h"
28 #include "ecmascript/object_factory.h"
29 #include "ecmascript/tagged_array.h"
30 #include "ecmascript/tests/test_helper.h"
31 #include "ecmascript/js_generator_object.h"
32
33 using namespace panda;
34 using namespace panda::ecmascript;
35
36 namespace panda::test {
37 using BuiltinsFunction = ecmascript::builtins::BuiltinsFunction;
38 class JSNApiTests : public testing::Test {
39 public:
SetUpTestCase()40 static void SetUpTestCase()
41 {
42 GTEST_LOG_(INFO) << "SetUpTestCase";
43 }
44
TearDownTestCase()45 static void TearDownTestCase()
46 {
47 GTEST_LOG_(INFO) << "TearDownCase";
48 }
49
SetUp()50 void SetUp() override
51 {
52 RuntimeOption option;
53 option.SetLogLevel(RuntimeOption::LOG_LEVEL::ERROR);
54 vm_ = JSNApi::CreateJSVM(option);
55 ASSERT_TRUE(vm_ != nullptr) << "Cannot create Runtime";
56 thread_ = vm_->GetJSThread();
57 vm_->SetEnableForceGC(true);
58 }
59
TearDown()60 void TearDown() override
61 {
62 vm_->SetEnableForceGC(false);
63 JSNApi::DestroyJSVM(vm_);
64 }
65
66 protected:
67 JSThread *thread_ = nullptr;
68 EcmaVM *vm_ = nullptr;
69 };
70
FunctionCallback(JsiRuntimeCallInfo * info)71 Local<JSValueRef> FunctionCallback(JsiRuntimeCallInfo* info)
72 {
73 EscapeLocalScope scope(info->GetVM());
74 return scope.Escape(ArrayRef::New(info->GetVM(), info->GetArgsNumber()));
75 }
76
WeakRefCallback(EcmaVM * vm)77 void WeakRefCallback(EcmaVM* vm)
78 {
79 LocalScope scope(vm);
80 Local<ObjectRef> object = ObjectRef::New(vm);
81 Global<ObjectRef> globalObject(vm, object);
82 globalObject.SetWeak();
83 Local<ObjectRef> object1 = ObjectRef::New(vm);
84 Global<ObjectRef> globalObject1(vm, object1);
85 globalObject1.SetWeak();
86 vm->CollectGarbage(TriggerGCType::YOUNG_GC);
87 vm->CollectGarbage(TriggerGCType::OLD_GC);
88 globalObject.FreeGlobalHandleAddr();
89 }
90
ThreadCheck(const EcmaVM * vm)91 void ThreadCheck(const EcmaVM *vm)
92 {
93 EXPECT_TRUE(vm->GetJSThread()->GetThreadId() != JSThread::GetCurrentThreadId());
94 }
95
HWTEST_F_L0(JSNApiTests,GetGlobalObject)96 HWTEST_F_L0(JSNApiTests, GetGlobalObject)
97 {
98 LocalScope scope(vm_);
99 Local<ObjectRef> globalObject = JSNApi::GetGlobalObject(vm_);
100 ASSERT_FALSE(globalObject.IsEmpty());
101 ASSERT_TRUE(globalObject->IsObject());
102 }
103
HWTEST_F_L0(JSNApiTests,ThreadIdCheck)104 HWTEST_F_L0(JSNApiTests, ThreadIdCheck)
105 {
106 EXPECT_TRUE(vm_->GetJSThread()->GetThreadId() == JSThread::GetCurrentThreadId());
107 }
108
HWTEST_F_L0(JSNApiTests,RegisterFunction)109 HWTEST_F_L0(JSNApiTests, RegisterFunction)
110 {
111 LocalScope scope(vm_);
112 Local<FunctionRef> callback = FunctionRef::New(vm_, FunctionCallback);
113 ASSERT_TRUE(!callback.IsEmpty());
114 std::vector<Local<JSValueRef>> arguments;
115 arguments.emplace_back(JSValueRef::Undefined(vm_));
116 Local<JSValueRef> result =
117 callback->Call(vm_, JSValueRef::Undefined(vm_), arguments.data(), arguments.size());
118 ASSERT_TRUE(result->IsArray(vm_));
119 Local<ArrayRef> array(result);
120 ASSERT_EQ(static_cast<uint64_t>(array->Length(vm_)), arguments.size());
121 }
122
HWTEST_F_L0(JSNApiTests,GetProperty)123 HWTEST_F_L0(JSNApiTests, GetProperty)
124 {
125 LocalScope scope(vm_);
126 Local<ObjectRef> globalObject = JSNApi::GetGlobalObject(vm_);
127 ASSERT_FALSE(globalObject.IsEmpty());
128 ASSERT_TRUE(globalObject->IsObject());
129
130 Local<ObjectRef> key = StringRef::NewFromUtf8(vm_, "Number");
131 Local<ObjectRef> property = globalObject->Get(vm_, key);
132 ASSERT_TRUE(property->IsFunction());
133 }
134
HWTEST_F_L0(JSNApiTests,SetProperty)135 HWTEST_F_L0(JSNApiTests, SetProperty)
136 {
137 LocalScope scope(vm_);
138 Local<ObjectRef> globalObject = JSNApi::GetGlobalObject(vm_);
139 ASSERT_FALSE(globalObject.IsEmpty());
140 ASSERT_TRUE(globalObject->IsObject());
141
142 Local<ArrayRef> property = ArrayRef::New(vm_, 3); // 3 : length
143 ASSERT_TRUE(property->IsArray(vm_));
144 ASSERT_EQ(property->Length(vm_), 3); // 3 : test case of input
145
146 Local<ObjectRef> key = StringRef::NewFromUtf8(vm_, "Test");
147 bool result = globalObject->Set(vm_, key, property);
148 ASSERT_TRUE(result);
149
150 Local<ObjectRef> propertyGet = globalObject->Get(vm_, key);
151 ASSERT_TRUE(propertyGet->IsArray(vm_));
152 ASSERT_EQ(Local<ArrayRef>(propertyGet)->Length(vm_), 3); // 3 : test case of input
153 }
154
HWTEST_F_L0(JSNApiTests,JsonParser)155 HWTEST_F_L0(JSNApiTests, JsonParser)
156 {
157 LocalScope scope(vm_);
158 Local<ObjectRef> globalObject = JSNApi::GetGlobalObject(vm_);
159 ASSERT_FALSE(globalObject.IsEmpty());
160 ASSERT_TRUE(globalObject->IsObject());
161
162 const char *const test{R"({"orientation": "portrait"})"};
163 Local<ObjectRef> jsonString = StringRef::NewFromUtf8(vm_, test);
164
165 Local<JSValueRef> result = JSON::Parse(vm_, jsonString);
166 ASSERT_TRUE(result->IsObject());
167
168 Local<ObjectRef> keyString = StringRef::NewFromUtf8(vm_, "orientation");
169 Local<JSValueRef> property = Local<ObjectRef>(result)->Get(vm_, keyString);
170 ASSERT_TRUE(property->IsString());
171 }
172
HWTEST_F_L0(JSNApiTests,StrictEqual)173 HWTEST_F_L0(JSNApiTests, StrictEqual)
174 {
175 LocalScope scope(vm_);
176 Local<StringRef> origin = StringRef::NewFromUtf8(vm_, "1");
177 Local<StringRef> target1 = StringRef::NewFromUtf8(vm_, "1");
178 Local<NumberRef> target = NumberRef::New(vm_, 1);
179
180 ASSERT_FALSE(origin->IsStrictEquals(vm_, target));
181 ASSERT_TRUE(origin->IsStrictEquals(vm_, target1));
182 }
183
HWTEST_F_L0(JSNApiTests,InstanceOf)184 HWTEST_F_L0(JSNApiTests, InstanceOf)
185 {
186 LocalScope scope(vm_);
187 Local<FunctionRef> target = FunctionRef::New(vm_, nullptr);
188 Local<ArrayRef> origin = ArrayRef::New(vm_, 1);
189
190 ASSERT_FALSE(origin->InstanceOf(vm_, target));
191 }
192
HWTEST_F_L0(JSNApiTests,TypeOf)193 HWTEST_F_L0(JSNApiTests, TypeOf)
194 {
195 LocalScope scope(vm_);
196 Local<StringRef> origin = StringRef::NewFromUtf8(vm_, "1");
197 Local<StringRef> typeString = origin->Typeof(vm_);
198 ASSERT_EQ(typeString->ToString(), "string");
199
200 Local<NumberRef> target = NumberRef::New(vm_, 1);
201 typeString = target->Typeof(vm_);
202 ASSERT_EQ(typeString->ToString(), "number");
203 }
204
HWTEST_F_L0(JSNApiTests,Symbol)205 HWTEST_F_L0(JSNApiTests, Symbol)
206 {
207 LocalScope scope(vm_);
208 Local<StringRef> description = StringRef::NewFromUtf8(vm_, "test");
209 Local<SymbolRef> symbol = SymbolRef::New(vm_, description);
210
211 ASSERT_FALSE(description->IsSymbol());
212 ASSERT_TRUE(symbol->IsSymbol());
213 }
214
HWTEST_F_L0(JSNApiTests,StringUtf8_001)215 HWTEST_F_L0(JSNApiTests, StringUtf8_001)
216 {
217 LocalScope scope(vm_);
218 std::string test = "Hello world";
219 Local<StringRef> testString = StringRef::NewFromUtf8(vm_, test.c_str());
220
221 EXPECT_EQ(testString->Utf8Length(vm_), 12); // 12 : length of testString("Hello World")
222 char buffer[12]; // 12 : length of testString
223 EXPECT_EQ(testString->WriteUtf8(buffer, 12), 12); // 12 : length of testString("Hello World")
224 std::string res(buffer);
225 ASSERT_EQ(res, test);
226 }
227
HWTEST_F_L0(JSNApiTests,StringUtf8_002)228 HWTEST_F_L0(JSNApiTests, StringUtf8_002)
229 {
230 LocalScope scope(vm_);
231 std::string test = "年";
232 Local<StringRef> testString = StringRef::NewFromUtf8(vm_, test.c_str());
233
234 EXPECT_EQ(testString->Utf8Length(vm_), 4); // 4 : length of testString("年")
235 char buffer[4]; // 4 : length of testString
236 EXPECT_EQ(testString->WriteUtf8(buffer, 4), 4); // 4 : length of testString("年")
237 std::string res(buffer);
238 ASSERT_EQ(res, test);
239 }
240
HWTEST_F_L0(JSNApiTests,StringUtf8_003)241 HWTEST_F_L0(JSNApiTests, StringUtf8_003)
242 {
243 LocalScope scope(vm_);
244 std::string str1 = "a";
245 std::string str2 = "b";
246 std::string test = str1 + '\0' + str2;
247
248 // isWriteBuffer == false, \u0000 ==> C080
249 Local<StringRef> testString1 = StringRef::NewFromUtf8(vm_, test.c_str(), test.length());
250 EXPECT_EQ(testString1->Utf8Length(vm_), 5);
251 char buffer1[4];
252 testString1->WriteUtf8(buffer1, 4, false);
253 EXPECT_EQ(buffer1[0], 'a');
254 EXPECT_EQ(buffer1[1], '\xC0');
255 EXPECT_EQ(buffer1[2], '\x80');
256 EXPECT_EQ(buffer1[3], 'b');
257
258 // isWriteBuffer == true, \u0000 ==> 0x00U
259 Local<StringRef> testString2 = StringRef::NewFromUtf8(vm_, test.c_str(), test.length());
260 EXPECT_EQ(testString2->Utf8Length(vm_), 5);
261 char buffer2[4];
262 testString2->WriteUtf8(buffer2, 4, true);
263 EXPECT_EQ(buffer2[0], 'a');
264 EXPECT_EQ(buffer2[1], '\0');
265 EXPECT_EQ(buffer2[2], 'b');
266 }
267
HWTEST_F_L0(JSNApiTests,StringLatin1_001)268 HWTEST_F_L0(JSNApiTests, StringLatin1_001)
269 {
270 LocalScope scope(vm_);
271 std::string test = "中";
272 Local<StringRef> testString = StringRef::NewFromUtf8(vm_, test.c_str());
273
274 EXPECT_EQ(testString->Length(), 1);
275 char buffer[1];
276 EXPECT_EQ(testString->WriteLatin1(buffer, 1), 1);
277
278 EXPECT_EQ(buffer[0], '-'); // '-' == 0x2D
279 }
280
HWTEST_F_L0(JSNApiTests,StringLatin1_002)281 HWTEST_F_L0(JSNApiTests, StringLatin1_002)
282 {
283 LocalScope scope(vm_);
284 std::string test = "En123";
285 Local<StringRef> testString = StringRef::NewFromUtf8(vm_, test.c_str());
286
287 EXPECT_EQ(testString->Length(), 5);
288 char buffer[5];
289 EXPECT_EQ(testString->WriteLatin1(buffer, 5), 5);
290
291 EXPECT_EQ(buffer[0], 'E');
292 EXPECT_EQ(buffer[1], 'n');
293 EXPECT_EQ(buffer[2], '1');
294 EXPECT_EQ(buffer[3], '2');
295 EXPECT_EQ(buffer[4], '3');
296 }
297
HWTEST_F_L0(JSNApiTests,ToType)298 HWTEST_F_L0(JSNApiTests, ToType)
299 {
300 LocalScope scope(vm_);
301 Local<StringRef> toString = StringRef::NewFromUtf8(vm_, "-123.3");
302 Local<JSValueRef> toValue(toString);
303
304 ASSERT_EQ(toString->ToNumber(vm_)->Value(), -123.3); // -123 : test case of input
305 ASSERT_EQ(toString->ToBoolean(vm_)->Value(), true);
306 ASSERT_EQ(toValue->ToString(vm_)->ToString(), "-123.3");
307 ASSERT_TRUE(toValue->ToObject(vm_)->IsObject());
308 }
309
HWTEST_F_L0(JSNApiTests,TypeValue)310 HWTEST_F_L0(JSNApiTests, TypeValue)
311 {
312 LocalScope scope(vm_);
313 Local<StringRef> toString = StringRef::NewFromUtf8(vm_, "-123");
314 Local<JSValueRef> toValue(toString);
315
316 ASSERT_EQ(toString->Int32Value(vm_), -123); // -123 : test case of input
317 ASSERT_EQ(toString->BooleaValue(), true);
318 ASSERT_EQ(toString->Uint32Value(vm_), 4294967173U); // 4294967173 : test case of input
319 ASSERT_EQ(toString->IntegerValue(vm_), -123); // -123 : test case of input
320 }
321
detach()322 void* detach()
323 {
324 GTEST_LOG_(INFO) << "detach is running";
325 return nullptr;
326 }
327
attach(void * buffer)328 void attach([[maybe_unused]] void* buffer)
329 {
330 GTEST_LOG_(INFO) << "attach is running";
331 }
332
HWTEST_F_L0(JSNApiTests,CreateNativeObject)333 HWTEST_F_L0(JSNApiTests, CreateNativeObject)
334 {
335 LocalScope scope(vm_);
336 Local<ObjectRef> object = ObjectRef::New(vm_, reinterpret_cast<void*>(detach), reinterpret_cast<void*>(attach));
337 Local<JSValueRef> key = StringRef::NewFromUtf8(vm_, "TestKey");
338 Local<JSValueRef> value = ObjectRef::New(vm_);
339 PropertyAttribute attribute(value, true, true, true);
340
341 ASSERT_TRUE(object->DefineProperty(vm_, key, attribute));
342 Local<JSValueRef> value1 = object->Get(vm_, key);
343 ASSERT_TRUE(value->IsStrictEquals(vm_, value1));
344 ASSERT_TRUE(object->Has(vm_, key));
345 ASSERT_TRUE(object->Delete(vm_, key));
346 ASSERT_FALSE(object->Has(vm_, key));
347 }
348
HWTEST_F_L0(JSNApiTests,DefineProperty)349 HWTEST_F_L0(JSNApiTests, DefineProperty)
350 {
351 LocalScope scope(vm_);
352 Local<ObjectRef> object = ObjectRef::New(vm_);
353 Local<JSValueRef> key = StringRef::NewFromUtf8(vm_, "TestKey");
354 Local<JSValueRef> value = ObjectRef::New(vm_);
355 PropertyAttribute attribute(value, true, true, true);
356
357 ASSERT_TRUE(object->DefineProperty(vm_, key, attribute));
358 Local<JSValueRef> value1 = object->Get(vm_, key);
359 ASSERT_TRUE(value->IsStrictEquals(vm_, value1));
360 }
361
HWTEST_F_L0(JSNApiTests,HasProperty)362 HWTEST_F_L0(JSNApiTests, HasProperty)
363 {
364 LocalScope scope(vm_);
365 Local<ObjectRef> object = ObjectRef::New(vm_);
366 Local<JSValueRef> key = StringRef::NewFromUtf8(vm_, "TestKey");
367 Local<JSValueRef> value = ObjectRef::New(vm_);
368 PropertyAttribute attribute(value, true, true, true);
369
370 ASSERT_TRUE(object->DefineProperty(vm_, key, attribute));
371 ASSERT_TRUE(object->Has(vm_, key));
372 }
373
HWTEST_F_L0(JSNApiTests,DeleteProperty)374 HWTEST_F_L0(JSNApiTests, DeleteProperty)
375 {
376 LocalScope scope(vm_);
377 Local<ObjectRef> object = ObjectRef::New(vm_);
378 Local<JSValueRef> key = StringRef::NewFromUtf8(vm_, "TestKey");
379 Local<JSValueRef> value = ObjectRef::New(vm_);
380 PropertyAttribute attribute(value, true, true, true);
381
382 ASSERT_TRUE(object->DefineProperty(vm_, key, attribute));
383 ASSERT_TRUE(object->Delete(vm_, key));
384 ASSERT_FALSE(object->Has(vm_, key));
385 }
386
HWTEST_F_L0(JSNApiTests,GetProtoType)387 HWTEST_F_L0(JSNApiTests, GetProtoType)
388 {
389 LocalScope scope(vm_);
390 Local<FunctionRef> function = FunctionRef::New(vm_, nullptr);
391 Local<JSValueRef> protoType = function->GetPrototype(vm_);
392 ASSERT_TRUE(protoType->IsObject());
393
394 Local<FunctionRef> object = ObjectRef::New(vm_);
395 protoType = object->GetPrototype(vm_);
396 ASSERT_TRUE(protoType->IsObject());
397
398 Local<FunctionRef> native = ObjectRef::New(vm_, reinterpret_cast<void*>(detach), reinterpret_cast<void*>(attach));
399 protoType = native->GetPrototype(vm_);
400 ASSERT_TRUE(protoType->IsObject());
401 }
402
CheckReject(JsiRuntimeCallInfo * info)403 void CheckReject(JsiRuntimeCallInfo* info)
404 {
405 ASSERT_EQ(info->GetArgsNumber(), 1U);
406 Local<JSValueRef> reason = info->GetCallArgRef(0);
407 ASSERT_TRUE(reason->IsString());
408 ASSERT_EQ(Local<StringRef>(reason)->ToString(), "Reject");
409 }
410
RejectCallback(JsiRuntimeCallInfo * info)411 Local<JSValueRef> RejectCallback(JsiRuntimeCallInfo* info)
412 {
413 LocalScope scope(info->GetVM());
414 CheckReject(info);
415 return JSValueRef::Undefined(info->GetVM());
416 }
417
HWTEST_F_L0(JSNApiTests,PromiseCatch)418 HWTEST_F_L0(JSNApiTests, PromiseCatch)
419 {
420 LocalScope scope(vm_);
421 Local<PromiseCapabilityRef> capability = PromiseCapabilityRef::New(vm_);
422
423 Local<PromiseRef> promise = capability->GetPromise(vm_);
424 Local<FunctionRef> reject = FunctionRef::New(vm_, RejectCallback);
425 Local<PromiseRef> catchPromise = promise->Catch(vm_, reject);
426 ASSERT_TRUE(promise->IsPromise());
427 ASSERT_TRUE(catchPromise->IsPromise());
428
429 Local<StringRef> reason = StringRef::NewFromUtf8(vm_, "Reject");
430 ASSERT_TRUE(capability->Reject(vm_, reason));
431
432 vm_->GetJSThread()->GetCurrentEcmaContext()->ExecutePromisePendingJob();
433 }
434
CheckResolve(JsiRuntimeCallInfo * info)435 void CheckResolve(JsiRuntimeCallInfo* info)
436 {
437 ASSERT_EQ(info->GetArgsNumber(), 1U);
438 Local<JSValueRef> value = info->GetCallArgRef(0);
439 ASSERT_TRUE(value->IsNumber());
440 ASSERT_EQ(Local<NumberRef>(value)->Value(), 300.3); // 300.3 : test case of input
441 }
442
ResolvedCallback(JsiRuntimeCallInfo * info)443 Local<JSValueRef> ResolvedCallback(JsiRuntimeCallInfo* info)
444 {
445 LocalScope scope(info->GetVM());
446 CheckResolve(info);
447 return JSValueRef::Undefined(info->GetVM());
448 }
449
HWTEST_F_L0(JSNApiTests,PromiseThen)450 HWTEST_F_L0(JSNApiTests, PromiseThen)
451 {
452 LocalScope scope(vm_);
453 Local<PromiseCapabilityRef> capability = PromiseCapabilityRef::New(vm_);
454
455 Local<PromiseRef> promise = capability->GetPromise(vm_);
456 Local<FunctionRef> resolve = FunctionRef::New(vm_, ResolvedCallback);
457 Local<FunctionRef> reject = FunctionRef::New(vm_, RejectCallback);
458 Local<PromiseRef> thenPromise = promise->Then(vm_, resolve, reject);
459 ASSERT_TRUE(promise->IsPromise());
460 ASSERT_TRUE(thenPromise->IsPromise());
461
462 Local<StringRef> value = NumberRef::New(vm_, 300.3); // 300.3 : test case of input
463 ASSERT_TRUE(capability->Resolve(vm_, value));
464 vm_->GetJSThread()->GetCurrentEcmaContext()->ExecutePromisePendingJob();
465 }
466
HWTEST_F_L0(JSNApiTests,Constructor)467 HWTEST_F_L0(JSNApiTests, Constructor)
468 {
469 LocalScope scope(vm_);
470 Local<ObjectRef> object = JSNApi::GetGlobalObject(vm_);
471 Local<StringRef> key = StringRef::NewFromUtf8(vm_, "Number");
472 Local<FunctionRef> numberConstructor = object->Get(vm_, key);
473 Local<JSValueRef> argv[1];
474 argv[0] = NumberRef::New(vm_, 1.3); // 1.3 : test case of input
475 Local<JSValueRef> result = numberConstructor->Constructor(vm_, argv, 1);
476 ASSERT_TRUE(result->IsObject());
477 ASSERT_EQ(result->ToNumber(vm_)->Value(), 1.3); // 1.3 : size of arguments
478 }
479
HWTEST_F_L0(JSNApiTests,ArrayBuffer)480 HWTEST_F_L0(JSNApiTests, ArrayBuffer)
481 {
482 LocalScope scope(vm_);
483 const int32_t length = 15;
484 Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
485 ASSERT_TRUE(arrayBuffer->IsArrayBuffer());
486 ASSERT_EQ(arrayBuffer->ByteLength(vm_), length);
487 ASSERT_NE(arrayBuffer->GetBuffer(), nullptr);
488 JSNApi::TriggerGC(vm_);
489 }
490
HWTEST_F_L0(JSNApiTests,ArrayBufferWithBuffer)491 HWTEST_F_L0(JSNApiTests, ArrayBufferWithBuffer)
492 {
493 static bool isFree = false;
494 struct Data {
495 int32_t length;
496 };
497 const int32_t length = 15;
498 Data *data = new Data();
499 data->length = length;
500 Deleter deleter = [](void *buffer, void *data) -> void {
501 delete[] reinterpret_cast<uint8_t *>(buffer);
502 Data *currentData = reinterpret_cast<Data *>(data);
503 ASSERT_EQ(currentData->length, 15); // 5 : size of arguments
504 delete currentData;
505 isFree = true;
506 };
507 {
508 LocalScope scope(vm_);
509 uint8_t *buffer = new uint8_t[length]();
510 Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, buffer, length, deleter, data);
511 ASSERT_TRUE(arrayBuffer->IsArrayBuffer());
512 ASSERT_EQ(arrayBuffer->ByteLength(vm_), length);
513 ASSERT_EQ(arrayBuffer->GetBuffer(), buffer);
514 }
515 JSNApi::TriggerGC(vm_, JSNApi::TRIGGER_GC_TYPE::FULL_GC);
516 ASSERT_TRUE(isFree);
517 }
518
HWTEST_F_L0(JSNApiTests,DataView)519 HWTEST_F_L0(JSNApiTests, DataView)
520 {
521 LocalScope scope(vm_);
522 const int32_t length = 15;
523 Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
524 JSNApi::TriggerGC(vm_);
525 ASSERT_TRUE(arrayBuffer->IsArrayBuffer());
526
527 // 5 : offset of byte, 7 : length
528 Local<DataViewRef> dataView = DataViewRef::New(vm_, arrayBuffer, 5, 7);
529 ASSERT_TRUE(dataView->IsDataView());
530 ASSERT_EQ(dataView->GetArrayBuffer(vm_)->GetBuffer(), arrayBuffer->GetBuffer());
531 ASSERT_EQ(dataView->ByteLength(), 7U); // 7 : size of arguments
532 ASSERT_EQ(dataView->ByteOffset(), 5U); // 5 : size of arguments
533
534 // 5 : offset of byte, 11 : length
535 dataView = DataViewRef::New(vm_, arrayBuffer, 5, 11);
536 ASSERT_TRUE(dataView->IsUndefined());
537 }
538
HWTEST_F_L0(JSNApiTests,Int8Array)539 HWTEST_F_L0(JSNApiTests, Int8Array)
540 {
541 LocalScope scope(vm_);
542 const int32_t length = 15;
543 Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
544 ASSERT_TRUE(arrayBuffer->IsArrayBuffer());
545
546 // 5 : offset of byte, 6 : length
547 Local<Int8ArrayRef> typedArray = Int8ArrayRef::New(vm_, arrayBuffer, 5, 6);
548 ASSERT_TRUE(typedArray->IsInt8Array());
549 ASSERT_EQ(typedArray->ByteLength(vm_), 6U); // 6 : length of bytes
550 ASSERT_EQ(typedArray->ByteOffset(vm_), 5U); // 5 : offset of byte
551 ASSERT_EQ(typedArray->ArrayLength(vm_), 6U); // 6 : length of array
552 ASSERT_EQ(typedArray->GetArrayBuffer(vm_)->GetBuffer(), arrayBuffer->GetBuffer());
553 }
554
HWTEST_F_L0(JSNApiTests,Uint8Array)555 HWTEST_F_L0(JSNApiTests, Uint8Array)
556 {
557 LocalScope scope(vm_);
558 const int32_t length = 15;
559 Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
560 ASSERT_TRUE(arrayBuffer->IsArrayBuffer());
561
562 // 5 : offset of byte, 6 : length
563 Local<Uint8ArrayRef> typedArray = Uint8ArrayRef::New(vm_, arrayBuffer, 5, 6);
564 ASSERT_TRUE(typedArray->IsUint8Array());
565 ASSERT_EQ(typedArray->ByteLength(vm_), 6U); // 6 : length of bytes
566 ASSERT_EQ(typedArray->ByteOffset(vm_), 5U); // 5 : offset of byte
567 ASSERT_EQ(typedArray->ArrayLength(vm_), 6U); // 6 : length of array
568 ASSERT_EQ(typedArray->GetArrayBuffer(vm_)->GetBuffer(), arrayBuffer->GetBuffer());
569 }
570
HWTEST_F_L0(JSNApiTests,Uint8ClampedArray)571 HWTEST_F_L0(JSNApiTests, Uint8ClampedArray)
572 {
573 LocalScope scope(vm_);
574 const int32_t length = 15;
575 Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
576 ASSERT_TRUE(arrayBuffer->IsArrayBuffer());
577
578 // 5 : offset of byte, 6 : length
579 Local<Uint8ClampedArrayRef> typedArray = Uint8ClampedArrayRef::New(vm_, arrayBuffer, 5, 6);
580 ASSERT_TRUE(typedArray->IsUint8ClampedArray());
581 ASSERT_EQ(typedArray->ByteLength(vm_), 6U); // 6 : length of bytes
582 ASSERT_EQ(typedArray->ByteOffset(vm_), 5U); // 5 : offset of byte
583 ASSERT_EQ(typedArray->ArrayLength(vm_), 6U); // 6 : length of array
584 ASSERT_EQ(typedArray->GetArrayBuffer(vm_)->GetBuffer(), arrayBuffer->GetBuffer());
585 }
586
HWTEST_F_L0(JSNApiTests,Int16Array)587 HWTEST_F_L0(JSNApiTests, Int16Array)
588 {
589 LocalScope scope(vm_);
590 const int32_t length = 30;
591 Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
592 ASSERT_TRUE(arrayBuffer->IsArrayBuffer());
593
594 // 4 : offset of byte, 6 : length
595 Local<Int16ArrayRef> typedArray = Int16ArrayRef::New(vm_, arrayBuffer, 4, 6);
596 ASSERT_TRUE(typedArray->IsInt16Array());
597 ASSERT_EQ(typedArray->ByteLength(vm_), 12U); // 12 : length of bytes
598 ASSERT_EQ(typedArray->ByteOffset(vm_), 4U); // 4 : offset of byte
599 ASSERT_EQ(typedArray->ArrayLength(vm_), 6U); // 6 : length of array
600 ASSERT_EQ(typedArray->GetArrayBuffer(vm_)->GetBuffer(), arrayBuffer->GetBuffer());
601 }
602
HWTEST_F_L0(JSNApiTests,Uint16Array)603 HWTEST_F_L0(JSNApiTests, Uint16Array)
604 {
605 LocalScope scope(vm_);
606 const int32_t length = 30;
607 Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
608 ASSERT_TRUE(arrayBuffer->IsArrayBuffer());
609
610 // 4 : offset of byte, 6 : length
611 Local<Uint16ArrayRef> typedArray = Uint16ArrayRef::New(vm_, arrayBuffer, 4, 6);
612 ASSERT_TRUE(typedArray->IsUint16Array());
613 ASSERT_EQ(typedArray->ByteLength(vm_), 12U); // 12 : length of bytes
614 ASSERT_EQ(typedArray->ByteOffset(vm_), 4U); // 4 : offset of byte
615 ASSERT_EQ(typedArray->ArrayLength(vm_), 6U); // 6 : length of array
616 ASSERT_EQ(typedArray->GetArrayBuffer(vm_)->GetBuffer(), arrayBuffer->GetBuffer());
617 }
618
HWTEST_F_L0(JSNApiTests,Uint32Array)619 HWTEST_F_L0(JSNApiTests, Uint32Array)
620 {
621 LocalScope scope(vm_);
622 const int32_t length = 30;
623 Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
624 ASSERT_TRUE(arrayBuffer->IsArrayBuffer());
625
626 // 4 : offset of byte, 6 : length
627 Local<Uint32ArrayRef> typedArray = Uint32ArrayRef::New(vm_, arrayBuffer, 4, 6);
628 ASSERT_TRUE(typedArray->IsUint32Array());
629 ASSERT_EQ(typedArray->ByteLength(vm_), 24U); // 24 : length of bytes
630 ASSERT_EQ(typedArray->ByteOffset(vm_), 4U); // 4 : offset of byte
631 ASSERT_EQ(typedArray->ArrayLength(vm_), 6U); // 6 : length of array
632 ASSERT_EQ(typedArray->GetArrayBuffer(vm_)->GetBuffer(), arrayBuffer->GetBuffer());
633 }
634
HWTEST_F_L0(JSNApiTests,Int32Array)635 HWTEST_F_L0(JSNApiTests, Int32Array)
636 {
637 LocalScope scope(vm_);
638 const int32_t length = 30;
639 Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
640 ASSERT_TRUE(arrayBuffer->IsArrayBuffer());
641
642 // 4 : offset of byte, 6 : length
643 Local<Int32ArrayRef> typedArray = Int32ArrayRef::New(vm_, arrayBuffer, 4, 6);
644 ASSERT_TRUE(typedArray->IsInt32Array());
645 ASSERT_EQ(typedArray->ByteLength(vm_), 24U); // 24 : length of bytes
646 ASSERT_EQ(typedArray->ByteOffset(vm_), 4U); // 4 : offset of byte
647 ASSERT_EQ(typedArray->ArrayLength(vm_), 6U); // 6 : length of array
648 ASSERT_EQ(typedArray->GetArrayBuffer(vm_)->GetBuffer(), arrayBuffer->GetBuffer());
649 }
650
HWTEST_F_L0(JSNApiTests,Float32Array)651 HWTEST_F_L0(JSNApiTests, Float32Array)
652 {
653 LocalScope scope(vm_);
654 const int32_t length = 30;
655 Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
656 ASSERT_TRUE(arrayBuffer->IsArrayBuffer());
657
658 // 4 : offset of byte, 6 : length
659 Local<Float32ArrayRef> typedArray = Float32ArrayRef::New(vm_, arrayBuffer, 4, 6);
660 ASSERT_TRUE(typedArray->IsFloat32Array());
661 ASSERT_EQ(typedArray->ByteLength(vm_), 24U); // 24 : length of bytes
662 ASSERT_EQ(typedArray->ByteOffset(vm_), 4U); // 4 : offset of byte
663 ASSERT_EQ(typedArray->ArrayLength(vm_), 6U); // 6 : length of array
664 ASSERT_EQ(typedArray->GetArrayBuffer(vm_)->GetBuffer(), arrayBuffer->GetBuffer());
665 }
666
HWTEST_F_L0(JSNApiTests,Float64Array)667 HWTEST_F_L0(JSNApiTests, Float64Array)
668 {
669 LocalScope scope(vm_);
670 const int32_t length = 57;
671 Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
672 ASSERT_TRUE(arrayBuffer->IsArrayBuffer());
673
674 // 8 : offset of byte, 6 : length
675 Local<Float64ArrayRef> typedArray = Float64ArrayRef::New(vm_, arrayBuffer, 8, 6);
676 ASSERT_TRUE(typedArray->IsFloat64Array());
677 ASSERT_EQ(typedArray->ByteLength(vm_), 48U); // 48 : length of bytes
678 ASSERT_EQ(typedArray->ByteOffset(vm_), 8U); // 8 : offset of byte
679 ASSERT_EQ(typedArray->ArrayLength(vm_), 6U); // 6 : length of array
680 ASSERT_EQ(typedArray->GetArrayBuffer(vm_)->GetBuffer(), arrayBuffer->GetBuffer());
681 }
682
HWTEST_F_L0(JSNApiTests,BigInt64Array)683 HWTEST_F_L0(JSNApiTests, BigInt64Array)
684 {
685 LocalScope scope(vm_);
686 const int32_t length = 57;
687 Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
688 ASSERT_TRUE(arrayBuffer->IsArrayBuffer());
689
690 // 8 : offset of byte, 6 : length
691 Local<BigInt64ArrayRef> typedArray = BigInt64ArrayRef::New(vm_, arrayBuffer, 8, 6);
692 ASSERT_TRUE(typedArray->IsBigInt64Array());
693 ASSERT_EQ(typedArray->ByteLength(vm_), 48U); // 48 : length of bytes
694 ASSERT_EQ(typedArray->ByteOffset(vm_), 8U); // 8 : offset of byte
695 ASSERT_EQ(typedArray->ArrayLength(vm_), 6U); // 6 : length of array
696 ASSERT_EQ(typedArray->GetArrayBuffer(vm_)->GetBuffer(), arrayBuffer->GetBuffer());
697 }
698
HWTEST_F_L0(JSNApiTests,BigUint64Array)699 HWTEST_F_L0(JSNApiTests, BigUint64Array)
700 {
701 LocalScope scope(vm_);
702 const int32_t length = 57;
703 Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
704 ASSERT_TRUE(arrayBuffer->IsArrayBuffer());
705
706 // 8 : offset of byte, 6 : length
707 Local<BigUint64ArrayRef> typedArray = BigUint64ArrayRef::New(vm_, arrayBuffer, 8, 6);
708 ASSERT_TRUE(typedArray->IsBigUint64Array());
709 ASSERT_EQ(typedArray->ByteLength(vm_), 48U); // 48 : length of bytes
710 ASSERT_EQ(typedArray->ByteOffset(vm_), 8U); // 8 : offset of byte
711 ASSERT_EQ(typedArray->ArrayLength(vm_), 6U); // 6 : length of array
712 ASSERT_EQ(typedArray->GetArrayBuffer(vm_)->GetBuffer(), arrayBuffer->GetBuffer());
713 }
714
HWTEST_F_L0(JSNApiTests,Error)715 HWTEST_F_L0(JSNApiTests, Error)
716 {
717 LocalScope scope(vm_);
718 Local<StringRef> message = StringRef::NewFromUtf8(vm_, "ErrorTest");
719 Local<JSValueRef> error = Exception::Error(vm_, message);
720 ASSERT_TRUE(error->IsError());
721
722 JSNApi::ThrowException(vm_, error);
723 ASSERT_TRUE(thread_->HasPendingException());
724 }
725
HWTEST_F_L0(JSNApiTests,RangeError)726 HWTEST_F_L0(JSNApiTests, RangeError)
727 {
728 LocalScope scope(vm_);
729 Local<StringRef> message = StringRef::NewFromUtf8(vm_, "ErrorTest");
730 Local<JSValueRef> error = Exception::RangeError(vm_, message);
731 ASSERT_TRUE(error->IsError());
732
733 JSNApi::ThrowException(vm_, error);
734 ASSERT_TRUE(thread_->HasPendingException());
735 }
736
HWTEST_F_L0(JSNApiTests,TypeError)737 HWTEST_F_L0(JSNApiTests, TypeError)
738 {
739 LocalScope scope(vm_);
740 Local<StringRef> message = StringRef::NewFromUtf8(vm_, "ErrorTest");
741 Local<JSValueRef> error = Exception::TypeError(vm_, message);
742 ASSERT_TRUE(error->IsError());
743
744 JSNApi::ThrowException(vm_, error);
745 ASSERT_TRUE(thread_->HasPendingException());
746 }
747
HWTEST_F_L0(JSNApiTests,ReferenceError)748 HWTEST_F_L0(JSNApiTests, ReferenceError)
749 {
750 LocalScope scope(vm_);
751 Local<StringRef> message = StringRef::NewFromUtf8(vm_, "ErrorTest");
752 Local<JSValueRef> error = Exception::ReferenceError(vm_, message);
753 ASSERT_TRUE(error->IsError());
754
755 JSNApi::ThrowException(vm_, error);
756 ASSERT_TRUE(thread_->HasPendingException());
757 }
758
HWTEST_F_L0(JSNApiTests,SyntaxError)759 HWTEST_F_L0(JSNApiTests, SyntaxError)
760 {
761 LocalScope scope(vm_);
762 Local<StringRef> message = StringRef::NewFromUtf8(vm_, "ErrorTest");
763 Local<JSValueRef> error = Exception::SyntaxError(vm_, message);
764 ASSERT_TRUE(error->IsError());
765
766 JSNApi::ThrowException(vm_, error);
767 ASSERT_TRUE(thread_->HasPendingException());
768 }
769
HWTEST_F_L0(JSNApiTests,OOMError)770 HWTEST_F_L0(JSNApiTests, OOMError)
771 {
772 LocalScope scope(vm_);
773 Local<StringRef> message = StringRef::NewFromUtf8(vm_, "ErrorTest");
774 Local<JSValueRef> error = Exception::OOMError(vm_, message);
775 ASSERT_TRUE(error->IsError());
776
777 JSNApi::ThrowException(vm_, error);
778 ASSERT_TRUE(thread_->HasPendingException());
779 }
780
HWTEST_F_L0(JSNApiTests,InheritPrototype_001)781 HWTEST_F_L0(JSNApiTests, InheritPrototype_001)
782 {
783 LocalScope scope(vm_);
784 JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
785 // new with Builtins::Set Prototype
786 JSHandle<JSTaggedValue> set = env->GetBuiltinsSetFunction();
787 Local<FunctionRef> setLocal = JSNApiHelper::ToLocal<FunctionRef>(set);
788 // new with Builtins::Map Prototype
789 JSHandle<JSTaggedValue> map = env->GetBuiltinsMapFunction();
790 Local<FunctionRef> mapLocal = JSNApiHelper::ToLocal<FunctionRef>(map);
791 JSHandle<JSTaggedValue> setPrototype(thread_, JSHandle<JSFunction>::Cast(set)->GetFunctionPrototype());
792 JSHandle<JSTaggedValue> mapPrototype(thread_, JSHandle<JSFunction>::Cast(map)->GetFunctionPrototype());
793 JSHandle<JSTaggedValue> mapPrototypeProto(thread_, JSTaggedValue::GetPrototype(thread_, mapPrototype));
794 bool same = JSTaggedValue::SameValue(setPrototype, mapPrototypeProto);
795 // before inherit, map.Prototype.__proto__ should be different from set.Prototype
796 ASSERT_FALSE(same);
797 // before inherit, map.__proto__ should be different from set
798 JSHandle<JSTaggedValue> mapProto(thread_, JSTaggedValue::GetPrototype(thread_, map));
799 bool same1 = JSTaggedValue::SameValue(set, mapProto);
800 ASSERT_FALSE(same1);
801
802 // Set property to Set Function
803 auto factory = vm_->GetFactory();
804 JSHandle<JSTaggedValue> defaultString = thread_->GlobalConstants()->GetHandledDefaultString();
805 PropertyDescriptor desc = PropertyDescriptor(thread_, defaultString);
806 bool success = JSObject::DefineOwnProperty(thread_, JSHandle<JSObject>::Cast(set), defaultString, desc);
807 ASSERT_TRUE(success);
808 JSHandle<JSTaggedValue> property1String(thread_, factory->NewFromASCII("property1").GetTaggedValue());
809 JSHandle<JSTaggedValue> func = env->GetTypedArrayFunction();
810 PropertyDescriptor desc1 = PropertyDescriptor(thread_, func);
811 bool success1 = JSObject::DefineOwnProperty(thread_, JSHandle<JSObject>::Cast(set), property1String, desc1);
812 ASSERT_TRUE(success1);
813
814 mapLocal->Inherit(vm_, setLocal);
815 JSHandle<JSTaggedValue> sonHandle = JSNApiHelper::ToJSHandle(mapLocal);
816 JSHandle<JSTaggedValue> sonPrototype(thread_, JSHandle<JSFunction>::Cast(sonHandle)->GetFunctionPrototype());
817 JSHandle<JSTaggedValue> sonPrototypeProto(thread_, JSTaggedValue::GetPrototype(thread_, sonPrototype));
818 bool same2 = JSTaggedValue::SameValue(setPrototype, sonPrototypeProto);
819 ASSERT_TRUE(same2);
820 JSHandle<JSTaggedValue> sonProto(thread_, JSTaggedValue::GetPrototype(thread_, map));
821 bool same3 = JSTaggedValue::SameValue(set, sonProto);
822 ASSERT_TRUE(same3);
823
824 // son = new Son(), Son() inherit from Parent(), Test whether son.InstanceOf(Parent) is true
825 JSHandle<JSObject> sonObj = factory->NewJSObjectByConstructor(JSHandle<JSFunction>::Cast(sonHandle), sonHandle);
826 bool isInstance = JSObject::InstanceOf(thread_, JSHandle<JSTaggedValue>::Cast(sonObj), set);
827 ASSERT_TRUE(isInstance);
828
829 // Test whether son Function can access to property of parent Function
830 OperationResult res = JSObject::GetProperty(thread_, JSHandle<JSObject>::Cast(sonHandle), defaultString);
831 bool same4 = JSTaggedValue::SameValue(defaultString, res.GetValue());
832 ASSERT_TRUE(same4);
833 OperationResult res1 = JSObject::GetProperty(thread_, JSHandle<JSObject>::Cast(sonHandle), property1String);
834 bool same5 = JSTaggedValue::SameValue(func, res1.GetValue());
835 ASSERT_TRUE(same5);
836
837 // new with empty Function Constructor
838 Local<FunctionRef> son1 = FunctionRef::New(vm_, FunctionCallback, nullptr);
839 son1->Inherit(vm_, mapLocal);
840 JSHandle<JSFunction> son1Handle = JSHandle<JSFunction>::Cast(JSNApiHelper::ToJSHandle(son1));
841 ASSERT_TRUE(son1Handle->HasFunctionPrototype());
842 }
843
HWTEST_F_L0(JSNApiTests,InheritPrototype_002)844 HWTEST_F_L0(JSNApiTests, InheritPrototype_002)
845 {
846 LocalScope scope(vm_);
847 JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
848 // new with Builtins::weakSet Prototype
849 JSHandle<JSTaggedValue> weakSet = env->GetBuiltinsWeakSetFunction();
850 Local<FunctionRef> weakSetLocal = JSNApiHelper::ToLocal<FunctionRef>(weakSet);
851 // new with Builtins::weakMap Prototype
852 JSHandle<JSTaggedValue> weakMap = env->GetBuiltinsWeakMapFunction();
853 Local<FunctionRef> weakMapLocal = JSNApiHelper::ToLocal<FunctionRef>(weakMap);
854
855 weakMapLocal->Inherit(vm_, weakSetLocal);
856
857 auto factory = vm_->GetFactory();
858 JSHandle<JSTaggedValue> property1String(thread_, factory->NewFromASCII("property1").GetTaggedValue());
859 JSHandle<JSTaggedValue> func = env->GetArrayFunction();
860 PropertyDescriptor desc1 = PropertyDescriptor(thread_, func);
861 bool success1 = JSObject::DefineOwnProperty(thread_, JSHandle<JSObject>::Cast(weakMap), property1String, desc1);
862 ASSERT_TRUE(success1);
863
864 JSHandle<JSTaggedValue> sonHandle = JSNApiHelper::ToJSHandle(weakMapLocal);
865 JSHandle<JSObject> sonObj =
866 factory->NewJSObjectByConstructor(JSHandle<JSFunction>::Cast(sonHandle), sonHandle);
867
868 JSHandle<JSTaggedValue> fatherHandle = JSNApiHelper::ToJSHandle(weakSetLocal);
869 JSHandle<JSObject> fatherObj =
870 factory->NewJSObjectByConstructor(JSHandle<JSFunction>::Cast(fatherHandle), fatherHandle);
871
872 JSHandle<JSTaggedValue> sonMethod =
873 JSObject::GetMethod(thread_, JSHandle<JSTaggedValue>(sonObj), property1String);
874 JSHandle<JSTaggedValue> fatherMethod =
875 JSObject::GetMethod(thread_, JSHandle<JSTaggedValue>(fatherObj), property1String);
876 bool same = JSTaggedValue::SameValue(sonMethod, fatherMethod);
877 ASSERT_TRUE(same);
878 }
879
HWTEST_F_L0(JSNApiTests,InheritPrototype_003)880 HWTEST_F_L0(JSNApiTests, InheritPrototype_003)
881 {
882 LocalScope scope(vm_);
883 JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
884 auto factory = vm_->GetFactory();
885
886 JSHandle<Method> invokeSelf =
887 factory->NewMethodForNativeFunction(reinterpret_cast<void *>(BuiltinsFunction::FunctionPrototypeInvokeSelf));
888 // father type
889 JSHandle<JSHClass> protoClass = JSHandle<JSHClass>::Cast(env->GetFunctionClassWithProto());
890 JSHandle<JSFunction> protoFunc = factory->NewJSFunctionByHClass(invokeSelf, protoClass);
891 Local<FunctionRef> protoLocal = JSNApiHelper::ToLocal<FunctionRef>(JSHandle<JSTaggedValue>(protoFunc));
892 // son type
893 JSHandle<JSHClass> noProtoClass = JSHandle<JSHClass>::Cast(env->GetFunctionClassWithoutProto());
894 JSHandle<JSFunction> noProtoFunc = factory->NewJSFunctionByHClass(invokeSelf, noProtoClass);
895 Local<FunctionRef> noProtoLocal = JSNApiHelper::ToLocal<FunctionRef>(JSHandle<JSTaggedValue>(noProtoFunc));
896
897 JSHandle<JSFunction> sonHandle = JSHandle<JSFunction>::Cast(JSNApiHelper::ToJSHandle(noProtoLocal));
898 EXPECT_FALSE(sonHandle->HasFunctionPrototype());
899
900 JSHandle<JSTaggedValue> defaultString = thread_->GlobalConstants()->GetHandledDefaultString();
901 PropertyDescriptor desc = PropertyDescriptor(thread_, defaultString);
902 JSObject::DefineOwnProperty(thread_, JSHandle<JSObject>::Cast(protoFunc), defaultString, desc);
903
904 noProtoLocal->Inherit(vm_, protoLocal);
905 JSHandle<JSFunction> son1Handle = JSHandle<JSFunction>::Cast(JSNApiHelper::ToJSHandle(noProtoLocal));
906 EXPECT_TRUE(son1Handle->HasFunctionPrototype());
907
908 OperationResult res = JSObject::GetProperty(thread_, JSHandle<JSObject>::Cast(son1Handle), defaultString);
909 EXPECT_EQ(JSTaggedValue::SameValue(defaultString, res.GetValue()), true);
910
911 JSHandle<JSTaggedValue> propertyString(thread_, factory->NewFromASCII("property").GetTaggedValue());
912 JSHandle<JSTaggedValue> func = env->GetArrayFunction();
913 PropertyDescriptor desc1 = PropertyDescriptor(thread_, func);
914 JSObject::DefineOwnProperty(thread_, JSHandle<JSObject>::Cast(protoFunc), propertyString, desc1);
915 OperationResult res1 = JSObject::GetProperty(thread_, JSHandle<JSObject>::Cast(son1Handle), propertyString);
916 EXPECT_EQ(JSTaggedValue::SameValue(func, res1.GetValue()), true);
917 }
918
HWTEST_F_L0(JSNApiTests,InheritPrototype_004)919 HWTEST_F_L0(JSNApiTests, InheritPrototype_004)
920 {
921 LocalScope scope(vm_);
922 JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
923 auto factory = vm_->GetFactory();
924
925 JSHandle<JSTaggedValue> weakSet = env->GetBuiltinsWeakSetFunction();
926 JSHandle<JSTaggedValue> deleteString(factory->NewFromASCII("delete"));
927 JSHandle<JSTaggedValue> addString(factory->NewFromASCII("add"));
928 JSHandle<JSTaggedValue> defaultString = thread_->GlobalConstants()->GetHandledDefaultString();
929 JSHandle<JSTaggedValue> deleteMethod = JSObject::GetMethod(thread_, weakSet, deleteString);
930 JSHandle<JSTaggedValue> addMethod = JSObject::GetMethod(thread_, weakSet, addString);
931
932 JSHandle<Method> invokeSelf =
933 factory->NewMethodForNativeFunction(reinterpret_cast<void *>(BuiltinsFunction::FunctionPrototypeInvokeSelf));
934 JSHandle<Method> ctor =
935 factory->NewMethodForNativeFunction(reinterpret_cast<void *>(BuiltinsFunction::FunctionConstructor));
936
937 JSHandle<JSHClass> protoClass = JSHandle<JSHClass>::Cast(env->GetFunctionClassWithProto());
938 JSHandle<JSFunction> funcFuncPrototype = factory->NewJSFunctionByHClass(invokeSelf, protoClass);
939 // add method in funcPrototype
940 PropertyDescriptor desc = PropertyDescriptor(thread_, deleteMethod);
941 JSObject::DefineOwnProperty(thread_, JSHandle<JSObject>::Cast(funcFuncPrototype), deleteString, desc);
942 JSHandle<JSTaggedValue> funcFuncPrototypeValue(funcFuncPrototype);
943
944 JSHandle<JSHClass> funcFuncProtoIntanceClass =
945 factory->NewEcmaHClass(JSFunction::SIZE, JSType::JS_FUNCTION, funcFuncPrototypeValue);
946 // new with NewJSFunctionByHClass::function Class
947 JSHandle<JSFunction> protoFunc =
948 factory->NewJSFunctionByHClass(ctor, funcFuncProtoIntanceClass);
949 EXPECT_TRUE(*protoFunc != nullptr);
950 // add method in funcnction
951 PropertyDescriptor desc1 = PropertyDescriptor(thread_, addMethod);
952 JSObject::DefineOwnProperty(thread_, JSHandle<JSObject>::Cast(protoFunc), addString, desc1);
953 JSObject::DefineOwnProperty(thread_, JSHandle<JSObject>::Cast(protoFunc), deleteString, desc);
954 // father type
955 Local<FunctionRef> protoLocal = JSNApiHelper::ToLocal<FunctionRef>(JSHandle<JSTaggedValue>(protoFunc));
956
957 JSHandle<JSHClass> noProtoClass = JSHandle<JSHClass>::Cast(env->GetFunctionClassWithoutProto());
958 JSHandle<JSFunction> funcFuncNoProtoPrototype = factory->NewJSFunctionByHClass(invokeSelf, noProtoClass);
959 JSHandle<JSTaggedValue> funcFuncNoProtoPrototypeValue(funcFuncNoProtoPrototype);
960
961 JSHandle<JSHClass> funcFuncNoProtoProtoIntanceClass =
962 factory->NewEcmaHClass(JSFunction::SIZE, JSType::JS_FUNCTION, funcFuncNoProtoPrototypeValue);
963 // new with NewJSFunctionByHClass::function Class
964 JSHandle<JSFunction> noProtoFunc = factory->NewJSFunctionByHClass(ctor,
965 funcFuncNoProtoProtoIntanceClass);
966 EXPECT_TRUE(*noProtoFunc != nullptr);
967 // set property that has same key with fater type
968 PropertyDescriptor desc2 = PropertyDescriptor(thread_, defaultString);
969 JSObject::DefineOwnProperty(thread_, JSHandle<JSObject>::Cast(noProtoFunc), addString, desc2);
970 // son type
971 Local<FunctionRef> noProtoLocal = JSNApiHelper::ToLocal<FunctionRef>(JSHandle<JSTaggedValue>(noProtoFunc));
972
973 noProtoLocal->Inherit(vm_, protoLocal);
974
975 JSHandle<JSFunction> sonHandle = JSHandle<JSFunction>::Cast(JSNApiHelper::ToJSHandle(noProtoLocal));
976 OperationResult res = JSObject::GetProperty(thread_, JSHandle<JSObject>::Cast(sonHandle), deleteString);
977 EXPECT_EQ(JSTaggedValue::SameValue(deleteMethod, res.GetValue()), true);
978 // test if the property value changed after inherit
979 OperationResult res1 = JSObject::GetProperty(thread_, JSHandle<JSObject>::Cast(sonHandle), addString);
980 EXPECT_EQ(JSTaggedValue::SameValue(defaultString, res1.GetValue()), true);
981 }
982
HWTEST_F_L0(JSNApiTests,ClassFunction)983 HWTEST_F_L0(JSNApiTests, ClassFunction)
984 {
985 LocalScope scope(vm_);
986 Local<FunctionRef> cls = FunctionRef::NewClassFunction(vm_, nullptr, nullptr, nullptr);
987
988 JSHandle<JSTaggedValue> clsObj = JSNApiHelper::ToJSHandle(Local<JSValueRef>(cls));
989 ASSERT_TRUE(clsObj->IsClassConstructor());
990
991 JSTaggedValue accessor = JSHandle<JSFunction>(clsObj)->GetPropertyInlinedProps(
992 JSFunction::CLASS_PROTOTYPE_INLINE_PROPERTY_INDEX);
993 ASSERT_TRUE(accessor.IsInternalAccessor());
994 }
995
HWTEST_F_L0(JSNApiTests,WeakRefSecondPassCallback)996 HWTEST_F_L0(JSNApiTests, WeakRefSecondPassCallback)
997 {
998 LocalScope scope(vm_);
999 Local<ObjectRef> object1 = ObjectRef::New(vm_);
1000 Global<ObjectRef> globalObject1(vm_, object1);
1001 globalObject1.SetWeak();
1002 NativeReferenceHelper *temp = nullptr;
1003 {
1004 LocalScope scope1(vm_);
1005 Local<ObjectRef> object2 = ObjectRef::New(vm_);
1006 Global<ObjectRef> globalObject2(vm_, object2);
1007 NativeReferenceHelper *ref1 = new NativeReferenceHelper(vm_, globalObject2, WeakRefCallback);
1008 ref1->SetWeakCallback();
1009 temp = ref1;
1010 }
1011 {
1012 LocalScope scope1(vm_);
1013 Local<ObjectRef> object3 = ObjectRef::New(vm_);
1014 Global<ObjectRef> globalObject3(vm_, object3);
1015 globalObject3.SetWeak();
1016 }
1017 Local<ObjectRef> object4 = ObjectRef::New(vm_);
1018 Global<ObjectRef> globalObject4(vm_, object4);
1019 NativeReferenceHelper *ref2 = new NativeReferenceHelper(vm_, globalObject4, WeakRefCallback);
1020 ref2->SetWeakCallback();
1021 vm_->CollectGarbage(TriggerGCType::OLD_GC);
1022 delete temp;
1023 delete ref2;
1024 }
1025
HWTEST_F_L0(JSNApiTests,TriggerGC_OLD_GC)1026 HWTEST_F_L0(JSNApiTests, TriggerGC_OLD_GC)
1027 {
1028 vm_->SetEnableForceGC(false);
1029 auto globalEnv = vm_->GetGlobalEnv();
1030 auto factory = vm_->GetFactory();
1031 JSHandle<JSTaggedValue> jsFunc = globalEnv->GetArrayFunction();
1032 JSHandle<JSObject> objVal1 =
1033 factory->NewJSObjectByConstructor(JSHandle<JSFunction>(jsFunc), jsFunc);
1034 JSHandle<JSObject> objVal2 =
1035 factory->NewJSObjectByConstructor(JSHandle<JSFunction>(jsFunc), jsFunc);
1036 JSObject *newObj2 = *objVal2;
1037 JSTaggedValue canBeGcValue(newObj2);
1038
1039 uint32_t arrayLength = 2;
1040 JSHandle<TaggedArray> taggedArray = factory->NewTaggedArray(arrayLength);
1041 taggedArray->Set(thread_, 0, objVal1);
1042 taggedArray->Set(thread_, 1, canBeGcValue);
1043 EXPECT_EQ(taggedArray->GetIdx(objVal1.GetTaggedValue()), 0U);
1044 EXPECT_EQ(taggedArray->GetIdx(canBeGcValue), 1U);
1045
1046 // trigger gc
1047 JSNApi::TRIGGER_GC_TYPE gcType = JSNApi::TRIGGER_GC_TYPE::OLD_GC;
1048 JSNApi::TriggerGC(vm_, gcType);
1049 EXPECT_EQ(taggedArray->GetIdx(objVal1.GetTaggedValue()), 0U);
1050 EXPECT_EQ(taggedArray->GetIdx(canBeGcValue), TaggedArray::MAX_ARRAY_INDEX);
1051
1052 vm_->SetEnableForceGC(true);
1053 }
1054
HWTEST_F_L0(JSNApiTests,ExecuteModuleBuffer)1055 HWTEST_F_L0(JSNApiTests, ExecuteModuleBuffer)
1056 {
1057 const char *fileName = "__JSNApiTests_ExecuteModuleBuffer.abc";
1058 const char *data = R"(
1059 .language ECMAScript
1060 .function any func_main_0(any a0, any a1, any a2) {
1061 ldai 1
1062 return
1063 }
1064 )";
1065 bool executeResult =
1066 JSNApi::ExecuteModuleBuffer(vm_, reinterpret_cast<const uint8_t *>(data), sizeof(data), fileName);
1067 EXPECT_FALSE(executeResult);
1068 }
1069
HWTEST_F_L0(JSNApiTests,addWorker_DeleteWorker)1070 HWTEST_F_L0(JSNApiTests, addWorker_DeleteWorker)
1071 {
1072 JSRuntimeOptions option;
1073 EcmaVM *workerVm = JSNApi::CreateEcmaVM(option);
1074 JSNApi::addWorker(vm_, workerVm);
1075 bool hasDeleted = JSNApi::DeleteWorker(vm_, workerVm);
1076 EXPECT_TRUE(hasDeleted);
1077
1078 hasDeleted = JSNApi::DeleteWorker(vm_, nullptr);
1079 EXPECT_FALSE(hasDeleted);
1080 }
1081
HWTEST_F_L0(JSNApiTests,PrimitiveRef_GetValue)1082 HWTEST_F_L0(JSNApiTests, PrimitiveRef_GetValue)
1083 {
1084 auto factory = vm_->GetFactory();
1085 Local<IntegerRef> intValue = IntegerRef::New(vm_, 0);
1086 EXPECT_EQ(intValue->Value(), 0);
1087
1088 Local<JSValueRef> jsValue = intValue->GetValue(vm_);
1089 EXPECT_TRUE(*jsValue == nullptr);
1090
1091 JSHandle<JSTaggedValue> nullHandle(thread_, JSTaggedValue::Null());
1092 JSHandle<JSHClass> jsClassHandle =
1093 factory->NewEcmaHClass(JSObject::SIZE, JSType::JS_PRIMITIVE_REF, nullHandle);
1094 TaggedObject *taggedObject = factory->NewObject(jsClassHandle);
1095 JSHandle<JSTaggedValue> jsTaggedValue(thread_, JSTaggedValue(taggedObject));
1096 Local<PrimitiveRef> jsValueRef = JSNApiHelper::ToLocal<JSPrimitiveRef>(jsTaggedValue);
1097 EXPECT_TRUE(*(jsValueRef->GetValue(vm_)) != nullptr);
1098 }
1099
HWTEST_F_L0(JSNApiTests,BigIntRef_New_Uint64)1100 HWTEST_F_L0(JSNApiTests, BigIntRef_New_Uint64)
1101 {
1102 uint64_t maxUint64 = std::numeric_limits<uint64_t>::max();
1103 Local<BigIntRef> maxBigintUint64 = BigIntRef::New(vm_, maxUint64);
1104 EXPECT_TRUE(maxBigintUint64->IsBigInt());
1105
1106 JSHandle<BigInt> maxBigintUint64Val(thread_, JSNApiHelper::ToJSTaggedValue(*maxBigintUint64));
1107 EXPECT_EQ(maxBigintUint64Val->GetDigit(0), static_cast<uint32_t>(maxUint64 & 0xffffffff));
1108 EXPECT_EQ(maxBigintUint64Val->GetDigit(1), static_cast<uint32_t>((maxUint64 >> BigInt::DATEBITS) & 0xffffffff));
1109
1110 uint64_t minUint64 = std::numeric_limits<uint64_t>::min();
1111 Local<BigIntRef> minBigintUint64 = BigIntRef::New(vm_, minUint64);
1112 EXPECT_TRUE(minBigintUint64->IsBigInt());
1113
1114 JSHandle<BigInt> minBigintUint64Val(thread_, JSNApiHelper::ToJSTaggedValue(*minBigintUint64));
1115 EXPECT_EQ(minBigintUint64Val->GetDigit(0), static_cast<uint32_t>(minUint64 & 0xffffffff));
1116 EXPECT_EQ(minBigintUint64Val->GetLength(), 1U);
1117 }
1118
HWTEST_F_L0(JSNApiTests,BigIntRef_New_Int64)1119 HWTEST_F_L0(JSNApiTests, BigIntRef_New_Int64)
1120 {
1121 int64_t maxInt64 = std::numeric_limits<int64_t>::max();
1122 Local<BigIntRef> maxBigintInt64 = BigIntRef::New(vm_, maxInt64);
1123 EXPECT_TRUE(maxBigintInt64->IsBigInt());
1124
1125 JSHandle<BigInt> maxBigintInt64Val(thread_, JSNApiHelper::ToJSTaggedValue(*maxBigintInt64));
1126 EXPECT_EQ(maxBigintInt64Val->GetDigit(0), static_cast<uint32_t>(maxInt64 & 0xffffffff));
1127 EXPECT_EQ(maxBigintInt64Val->GetDigit(1), static_cast<uint32_t>((maxInt64 >> BigInt::DATEBITS) & 0xffffffff));
1128
1129 int64_t minInt64 = std::numeric_limits<int64_t>::min();
1130 Local<BigIntRef> minBigintInt64 = BigIntRef::New(vm_, minInt64);
1131 EXPECT_TRUE(minBigintInt64->IsBigInt());
1132
1133 JSHandle<BigInt> minBigintInt64Val(thread_, JSNApiHelper::ToJSTaggedValue(*minBigintInt64));
1134 EXPECT_EQ(minBigintInt64Val->GetSign(), true);
1135 EXPECT_EQ(minBigintInt64Val->GetDigit(0), static_cast<uint32_t>((-minInt64) & 0xffffffff));
1136 EXPECT_EQ(minBigintInt64Val->GetDigit(1), static_cast<uint32_t>(((-minInt64) >> BigInt::DATEBITS) & 0xffffffff));
1137 }
1138
HWTEST_F_L0(JSNApiTests,BigIntRef_CreateBigWords_GetWordsArray_GetWordsArraySize)1139 HWTEST_F_L0(JSNApiTests, BigIntRef_CreateBigWords_GetWordsArray_GetWordsArraySize)
1140 {
1141 bool sign = false;
1142 uint32_t size = 3;
1143 const uint32_t MULTIPLE = 2;
1144 const uint64_t words[3] = {
1145 std::numeric_limits<uint64_t>::min() - 1,
1146 std::numeric_limits<uint64_t>::min(),
1147 std::numeric_limits<uint64_t>::max(),
1148 };
1149 Local<JSValueRef> bigWords = BigIntRef::CreateBigWords(vm_, sign, size, words);
1150 EXPECT_TRUE(bigWords->IsBigInt());
1151
1152 Local<BigIntRef> bigWordsRef(bigWords);
1153 EXPECT_EQ(bigWordsRef->GetWordsArraySize(), size);
1154
1155 JSHandle<BigInt> bigintUint64Val(thread_, JSNApiHelper::ToJSTaggedValue(*bigWords));
1156 EXPECT_EQ(bigintUint64Val->GetSign(), false);
1157 EXPECT_EQ(bigintUint64Val->GetLength(), size * MULTIPLE);
1158
1159 bool resultSignBit = true;
1160 uint64_t *resultWords = new uint64_t[3](); // 3 : length of words array
1161 bigWordsRef->GetWordsArray(&resultSignBit, size, resultWords);
1162 EXPECT_EQ(resultSignBit, false);
1163 EXPECT_EQ(resultWords[0], words[0]);
1164 EXPECT_EQ(resultWords[1], words[1]);
1165 EXPECT_EQ(resultWords[2], words[2]);
1166 delete[] resultWords;
1167 }
1168
HWTEST_F_L0(JSNApiTests,DateRef_New_ToString_GetTime)1169 HWTEST_F_L0(JSNApiTests, DateRef_New_ToString_GetTime)
1170 {
1171 double time = 1.1;
1172 Local<DateRef> data = DateRef::New(vm_, time);
1173 EXPECT_TRUE(data->IsDate());
1174
1175 Local<StringRef> tostring = data->ToString(vm_);
1176 Local<JSValueRef> toValue(tostring);
1177 EXPECT_TRUE(tostring->IsString());
1178 double dou = data->GetTime();
1179 EXPECT_EQ(dou, 1.1);
1180 }
1181
HWTEST_F_L0(JSNApiTests,PromiseRef_Finally)1182 HWTEST_F_L0(JSNApiTests, PromiseRef_Finally)
1183 {
1184 LocalScope scope(vm_);
1185 Local<PromiseCapabilityRef> capability = PromiseCapabilityRef::New(vm_);
1186
1187 Local<PromiseRef> promise = capability->GetPromise(vm_);
1188 Local<FunctionRef> reject = FunctionRef::New(vm_, RejectCallback);
1189 Local<PromiseRef> catchPromise = promise->Finally(vm_, reject);
1190 ASSERT_TRUE(promise->IsPromise());
1191 ASSERT_TRUE(catchPromise->IsPromise());
1192 Local<PromiseRef> catchPromise1 = promise->Then(vm_, reject, reject);
1193 ASSERT_TRUE(catchPromise1->IsPromise());
1194 Local<FunctionRef> callback = FunctionRef::New(vm_, FunctionCallback);
1195 ASSERT_TRUE(!callback.IsEmpty());
1196 Local<PromiseRef> catchPromise2 = promise->Then(vm_, callback);
1197 ASSERT_TRUE(catchPromise2->IsPromise());
1198 }
1199
HWTEST_F_L0(JSNApiTests,JSNApi_SerializeValue)1200 HWTEST_F_L0(JSNApiTests, JSNApi_SerializeValue)
1201 {
1202 LocalScope scope(vm_);
1203 Local<FunctionRef> callback = FunctionRef::New(vm_, FunctionCallback);
1204 ASSERT_TRUE(!callback.IsEmpty());
1205 std::vector<Local<JSValueRef>> arguments;
1206 arguments.emplace_back(JSValueRef::Undefined(vm_));
1207 Local<JSValueRef> result =
1208 callback->Call(vm_, JSValueRef::Undefined(vm_), arguments.data(), arguments.size());
1209 ASSERT_TRUE(result->IsArray(vm_));
1210 Local<ArrayRef> array(result);
1211 ASSERT_EQ(static_cast<uint64_t>(array->Length(vm_)), arguments.size());
1212 void* res = nullptr;
1213 res = JSNApi::SerializeValue(vm_, result, result);
1214 EXPECT_TRUE(res);
1215 }
1216
HWTEST_F_L0(JSNApiTests,JSNApi_SetHostPromiseRejectionTracker)1217 HWTEST_F_L0(JSNApiTests, JSNApi_SetHostPromiseRejectionTracker)
1218 {
1219 void *data = reinterpret_cast<void *>(BuiltinsFunction::FunctionPrototypeInvokeSelf);
1220 JSNApi::SetHostPromiseRejectionTracker(vm_, data, data);
1221 PromiseRejectCallback res = vm_->GetJSThread()->GetCurrentEcmaContext()->GetPromiseRejectCallback();
1222 ASSERT_EQ(res, reinterpret_cast<ecmascript::PromiseRejectCallback>(data));
1223 }
1224
HWTEST_F_L0(JSNApiTests,JSNApi_SetNativePtrGetter_SetHostEnqueueJob)1225 HWTEST_F_L0(JSNApiTests, JSNApi_SetNativePtrGetter_SetHostEnqueueJob)
1226 {
1227 void *cb = reinterpret_cast<void *>(BuiltinsFunction::FunctionPrototypeInvokeSelf);
1228 JSNApi::SetNativePtrGetter(vm_, cb);
1229 NativePtrGetter res = vm_->GetNativePtrGetter();
1230 ASSERT_EQ(res, reinterpret_cast<ecmascript::NativePtrGetter>(cb));
1231 }
1232
HWTEST_F_L0(JSNApiTests,NumberRef_New)1233 HWTEST_F_L0(JSNApiTests, NumberRef_New)
1234 {
1235 uint32_t input = 32;
1236 int64_t input1 = 1;
1237 Local<NumberRef> res = NumberRef::New(vm_, input);
1238 Local<NumberRef> res1 = NumberRef::New(vm_, input1);
1239 ASSERT_TRUE(res->IsNumber());
1240 ASSERT_TRUE(res1->IsNumber());
1241 }
1242
HWTEST_F_L0(JSNApiTests,ObjectRef_Set)1243 HWTEST_F_L0(JSNApiTests, ObjectRef_Set)
1244 {
1245 LocalScope scope(vm_);
1246 Local<ObjectRef> object = ObjectRef::New(vm_);
1247 void *data1 = reinterpret_cast<void *>(BuiltinsFunction::FunctionPrototypeInvokeSelf);
1248 void *data2 = reinterpret_cast<void *>(BuiltinsFunction::FunctionPrototypeInvokeSelf);
1249 bool res = object->Set(vm_, data1, data2);
1250 ASSERT_TRUE(res);
1251 }
1252
HWTEST_F_L0(JSNApiTests,ObjectRef_GetOwnEnumerablePropertyNames)1253 HWTEST_F_L0(JSNApiTests, ObjectRef_GetOwnEnumerablePropertyNames)
1254 {
1255 LocalScope scope(vm_);
1256 Local<ObjectRef> object = ObjectRef::New(vm_);
1257 Local<ArrayRef> res = object->GetOwnEnumerablePropertyNames(vm_);
1258 ASSERT_TRUE(res->IsArray(vm_));
1259 }
1260
HWTEST_F_L0(JSNApiTests,ObjectRef_SetNativePointerFieldCount_GetNativePointerFieldCount)1261 HWTEST_F_L0(JSNApiTests, ObjectRef_SetNativePointerFieldCount_GetNativePointerFieldCount)
1262 {
1263 LocalScope scope(vm_);
1264 Local<ObjectRef> object = ObjectRef::New(vm_);
1265 int32_t input = 34;
1266 object->SetNativePointerFieldCount(input);
1267 int32_t res = object->GetNativePointerFieldCount();
1268 ASSERT_EQ(res, input);
1269 NativePointerCallback callBack = nullptr;
1270 void *vp1 = static_cast<void*>(new std::string("test"));
1271 void *vp2 = static_cast<void*>(new std::string("test"));
1272 std::string *sp1 = static_cast<std::string*>(vp1);
1273 object->SetNativePointerField(33, vp1, callBack, vp2);
1274 void *res1 = object->GetNativePointerField(33);
1275 std::string *sp2 = static_cast<std::string*>(res1);
1276 ASSERT_EQ(sp1, sp2);
1277 }
1278
HWTEST_F_L0(JSNApiTests,FunctionRef_GetFunctionPrototype_SetName_GetName)1279 HWTEST_F_L0(JSNApiTests, FunctionRef_GetFunctionPrototype_SetName_GetName)
1280 {
1281 LocalScope scope(vm_);
1282 Deleter deleter = nullptr;
1283 void *cb = reinterpret_cast<void *>(BuiltinsFunction::FunctionPrototypeInvokeSelf);
1284 bool callNative = true;
1285 size_t nativeBindingsize = 15;
1286 Local<FunctionRef> res = FunctionRef::NewClassFunction(vm_, FunctionCallback,
1287 deleter, cb, callNative, nativeBindingsize);
1288 ASSERT_TRUE(res->IsFunction());
1289 Local<JSValueRef> res1 = res->GetFunctionPrototype(vm_);
1290 ASSERT_TRUE(!res1->IsArray(vm_));
1291 Local<StringRef> origin = StringRef::NewFromUtf8(vm_, "1");
1292 res->SetName(vm_, origin);
1293 Local<StringRef> s = res->GetName(vm_);
1294 std::string str = s->ToString();
1295 ASSERT_EQ("1", str);
1296 }
1297
HWTEST_F_L0(JSNApiTests,JSNApi_SetAssetPath_GetAssetPath)1298 HWTEST_F_L0(JSNApiTests, JSNApi_SetAssetPath_GetAssetPath)
1299 {
1300 LocalScope scope(vm_);
1301 std::string str = "11";
1302 JSNApi::SetAssetPath(vm_, str);
1303 std::string res = JSNApi::GetAssetPath(vm_);
1304 ASSERT_EQ(str, res);
1305 void *data = reinterpret_cast<void *>(BuiltinsFunction::FunctionPrototypeInvokeSelf);
1306 JSNApi::SetLoop(vm_, data);
1307 void* res1 = vm_->GetLoop();
1308 ASSERT_EQ(res1, data);
1309 }
1310
HWTEST_F_L0(JSNApiTests,JSValueRef_ToNativePointer)1311 HWTEST_F_L0(JSNApiTests, JSValueRef_ToNativePointer)
1312 {
1313 LocalScope scope(vm_);
1314 Local<StringRef> toString = StringRef::NewFromUtf8(vm_, "-123.3");
1315 Local<JSValueRef> toValue(toString);
1316 ASSERT_EQ(toString->ToNumber(vm_)->Value(), -123.3); // -123 : test case of input
1317 ASSERT_EQ(toString->ToBoolean(vm_)->Value(), true);
1318 ASSERT_EQ(toValue->ToString(vm_)->ToString(), "-123.3");
1319 ASSERT_TRUE(toValue->ToObject(vm_)->IsObject());
1320 Local<NativePointerRef> res = toValue->ToNativePointer(vm_);
1321 ASSERT_TRUE(res->IsString());
1322 }
1323
HWTEST_F_L0(JSNApiTests,GeneratorObjectRef_IsGenerator)1324 HWTEST_F_L0(JSNApiTests, GeneratorObjectRef_IsGenerator)
1325 {
1326 ObjectFactory *factory = vm_->GetFactory();
1327 auto env = vm_->GetGlobalEnv();
1328
1329 JSHandle<JSTaggedValue> genFunc = env->GetGeneratorFunctionFunction();
1330 JSHandle<JSGeneratorObject> genObjHandleVal = factory->NewJSGeneratorObject(genFunc);
1331
1332 JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetGeneratorFunctionClass());
1333 JSHandle<JSFunction> generatorFunc = JSHandle<JSFunction>::Cast(factory->NewJSObject(hclass));
1334 JSFunction::InitializeJSFunction(thread_, generatorFunc, FunctionKind::GENERATOR_FUNCTION);
1335
1336 JSHandle<GeneratorContext> generatorContext = factory->NewGeneratorContext();
1337 generatorContext->SetMethod(thread_, generatorFunc.GetTaggedValue());
1338
1339 JSHandle<JSTaggedValue> generatorContextVal = JSHandle<JSTaggedValue>::Cast(generatorContext);
1340 genObjHandleVal->SetGeneratorContext(thread_, generatorContextVal.GetTaggedValue());
1341
1342 JSHandle<JSTaggedValue> genObjTagHandleVal = JSHandle<JSTaggedValue>::Cast(genObjHandleVal);
1343 Local<GeneratorObjectRef> genObjectRef = JSNApiHelper::ToLocal<GeneratorObjectRef>(genObjTagHandleVal);
1344 Local<JSValueRef> res = genObjectRef->GetGeneratorFunction(vm_);
1345 ASSERT_TRUE(res->IsGeneratorFunction());
1346 }
1347
HWTEST_F_L0(JSNApiTests,BigIntToInt64)1348 HWTEST_F_L0(JSNApiTests, BigIntToInt64)
1349 {
1350 LocalScope scope(vm_);
1351 uint64_t maxUint64 = std::numeric_limits<uint64_t>::max();
1352 Local<BigIntRef> maxBigintUint64 = BigIntRef::New(vm_, maxUint64);
1353 EXPECT_TRUE(maxBigintUint64->IsBigInt());
1354 int64_t num = -11;
1355 int64_t num1 = num;
1356 bool lossless = true;
1357 maxBigintUint64->BigIntToInt64(vm_, &num, &lossless);
1358 EXPECT_TRUE(num != num1);
1359 }
1360
HWTEST_F_L0(JSNApiTests,BigIntToUint64)1361 HWTEST_F_L0(JSNApiTests, BigIntToUint64)
1362 {
1363 LocalScope scope(vm_);
1364 uint64_t maxUint64 = std::numeric_limits<uint64_t>::max();
1365 Local<BigIntRef> maxBigintUint64 = BigIntRef::New(vm_, maxUint64);
1366 EXPECT_TRUE(maxBigintUint64->IsBigInt());
1367 uint64_t num = -11;
1368 uint64_t num1 = num;
1369 bool lossless = true;
1370 maxBigintUint64->BigIntToUint64(vm_, &num, &lossless);
1371 EXPECT_TRUE(num != num1);
1372 }
1373
HWTEST_F_L0(JSNApiTests,BooleanRef_New)1374 HWTEST_F_L0(JSNApiTests, BooleanRef_New)
1375 {
1376 LocalScope scope(vm_);
1377 bool input = true;
1378 Local<BooleanRef> res = BooleanRef::New(vm_, input);
1379 EXPECT_TRUE(res->IsBoolean());
1380 EXPECT_TRUE(res->BooleaValue());
1381 }
1382
HWTEST_F_L0(JSNApiTests,NewFromUnsigned)1383 HWTEST_F_L0(JSNApiTests, NewFromUnsigned)
1384 {
1385 LocalScope scope(vm_);
1386 unsigned int input = 1;
1387 [[maybe_unused]] Local<IntegerRef> res = IntegerRef::NewFromUnsigned(vm_, input);
1388 EXPECT_TRUE(res->IntegerValue(vm_) == 1);
1389 EXPECT_TRUE(res->Value() == 1);
1390 }
1391
HWTEST_F_L0(JSNApiTests,SetBundleName_GetBundleName)1392 HWTEST_F_L0(JSNApiTests, SetBundleName_GetBundleName)
1393 {
1394 LocalScope scope(vm_);
1395 std::string str = "11";
1396 JSNApi::SetBundleName(vm_, str);
1397 std::string res = JSNApi::GetBundleName(vm_);
1398 ASSERT_EQ(str, res);
1399 }
1400
HWTEST_F_L0(JSNApiTests,SetModuleName_GetModuleName)1401 HWTEST_F_L0(JSNApiTests, SetModuleName_GetModuleName)
1402 {
1403 LocalScope scope(vm_);
1404 std::string str = "11";
1405 JSNApi::SetModuleName(vm_, str);
1406 std::string res = JSNApi::GetModuleName(vm_);
1407 ASSERT_EQ(str, res);
1408 }
1409
HWTEST_F_L0(JSNApiTests,IsBundle)1410 HWTEST_F_L0(JSNApiTests, IsBundle)
1411 {
1412 LocalScope scope(vm_);
1413 bool res = JSNApi::IsBundle(vm_);
1414 ASSERT_EQ(res, true);
1415 }
1416
HWTEST_F_L0(JSNApiTests,MapRef_GetSize_GetTotalElements_Get_GetKey_GetValue_New_Set)1417 HWTEST_F_L0(JSNApiTests, MapRef_GetSize_GetTotalElements_Get_GetKey_GetValue_New_Set)
1418 {
1419 LocalScope scope(vm_);
1420 Local<MapRef> map = MapRef::New(vm_);
1421 Local<JSValueRef> key = StringRef::NewFromUtf8(vm_, "TestKey");
1422 Local<JSValueRef> value = StringRef::NewFromUtf8(vm_, "TestValue");
1423 map->Set(vm_, key, value);
1424 Local<JSValueRef> res = map->Get(vm_, key);
1425 ASSERT_EQ(res->ToString(vm_)->ToString(), value->ToString(vm_)->ToString());
1426 int32_t num = map->GetSize();
1427 int32_t num1 = map->GetTotalElements();
1428 ASSERT_EQ(num, 1);
1429 ASSERT_EQ(num1, 1);
1430 Local<JSValueRef> res1 = map->GetKey(vm_, 0);
1431 ASSERT_EQ(res1->ToString(vm_)->ToString(), key->ToString(vm_)->ToString());
1432 Local<JSValueRef> res2 = map->GetValue(vm_, 0);
1433 ASSERT_EQ(res2->ToString(vm_)->ToString(), value->ToString(vm_)->ToString());
1434 }
1435
HWTEST_F_L0(JSNApiTests,GetSourceCode)1436 HWTEST_F_L0(JSNApiTests, GetSourceCode)
1437 {
1438 LocalScope scope(vm_);
1439 Local<FunctionRef> callback = FunctionRef::New(vm_, FunctionCallback);
1440 bool res = callback->IsNative(vm_);
1441 EXPECT_TRUE(res);
1442 }
1443
HWTEST_F_L0(JSNApiTests,ObjectRef_Delete)1444 HWTEST_F_L0(JSNApiTests, ObjectRef_Delete)
1445 {
1446 LocalScope scope(vm_);
1447 Local<ObjectRef> object = ObjectRef::New(vm_);
1448 Local<JSValueRef> key = StringRef::NewFromUtf8(vm_, "TestKey");
1449 Local<JSValueRef> value = ObjectRef::New(vm_);
1450 PropertyAttribute attribute(value, true, true, true);
1451 ASSERT_TRUE(object->DefineProperty(vm_, key, attribute));
1452 ASSERT_TRUE(object->Delete(vm_, key));
1453 ASSERT_FALSE(object->Has(vm_, key));
1454 }
1455
HWTEST_F_L0(JSNApiTests,ObjectRef_Set1)1456 HWTEST_F_L0(JSNApiTests, ObjectRef_Set1)
1457 {
1458 LocalScope scope(vm_);
1459 Local<ObjectRef> object = ObjectRef::New(vm_);
1460 Local<StringRef> toString = StringRef::NewFromUtf8(vm_, "-123.3");
1461 Local<JSValueRef> toValue(toString);
1462 bool res = object->Set(vm_, 12, toValue);
1463 ASSERT_TRUE(res);
1464 Local<JSValueRef> res1 = object->Get(vm_, 12);
1465 ASSERT_EQ(res1->ToString(vm_)->ToString(), toValue->ToString(vm_)->ToString());
1466 }
1467
HWTEST_F_L0(JSNApiTests,NativePointerRef_New)1468 HWTEST_F_L0(JSNApiTests, NativePointerRef_New)
1469 {
1470 LocalScope scope(vm_);
1471 NativePointerCallback callBack = nullptr;
1472 void *vp1 = static_cast<void*>(new std::string("test"));
1473 void *vp2 = static_cast<void*>(new std::string("test"));
1474 Local<NativePointerRef> res = NativePointerRef::New(vm_, vp1, callBack, vp2, 0);
1475 ASSERT_EQ(res->Value(), vp1);
1476 }
1477
HWTEST_F_L0(JSNApiTests,ObjectRef_Has_Delete)1478 HWTEST_F_L0(JSNApiTests, ObjectRef_Has_Delete)
1479 {
1480 LocalScope scope(vm_);
1481 Local<ObjectRef> object = ObjectRef::New(vm_);
1482 uint32_t num = 10;
1483 Local<StringRef> toString = StringRef::NewFromUtf8(vm_, "-123.3");
1484 Local<JSValueRef> toValue(toString);
1485 bool res = object->Set(vm_, num, toValue);
1486 ASSERT_TRUE(res);
1487 bool res1 = object->Has(vm_, num);
1488 ASSERT_TRUE(res1);
1489 bool res2 = object->Delete(vm_, num);
1490 ASSERT_TRUE(res2);
1491 bool res3 = object->Has(vm_, num);
1492 ASSERT_FALSE(res3);
1493 }
1494
HWTEST_F_L0(JSNApiTests,PromiseRejectInfo_GetData)1495 HWTEST_F_L0(JSNApiTests, PromiseRejectInfo_GetData)
1496 {
1497 LocalScope scope(vm_);
1498 Local<StringRef> toString = StringRef::NewFromUtf8(vm_, "-123.3");
1499 Local<JSValueRef> promise(toString);
1500 Local<StringRef> toString1 = StringRef::NewFromUtf8(vm_, "123.3");
1501 Local<JSValueRef> reason(toString1);
1502 void *data = static_cast<void*>(new std::string("test"));
1503 PromiseRejectInfo promisereject(promise, reason, PromiseRejectInfo::PROMISE_REJECTION_EVENT::REJECT, data);
1504 Local<JSValueRef> promise_res = promisereject.GetPromise();
1505 Local<JSValueRef> reason_res = promisereject.GetReason();
1506 ASSERT_EQ(promise_res->ToString(vm_)->ToString(), promise->ToString(vm_)->ToString());
1507 ASSERT_EQ(reason_res->ToString(vm_)->ToString(), reason->ToString(vm_)->ToString());
1508 void* dataRes = promisereject.GetData();
1509 ASSERT_EQ(dataRes, data);
1510 }
1511
HWTEST_F_L0(JSNApiTests,FunctionCallScope)1512 HWTEST_F_L0(JSNApiTests, FunctionCallScope)
1513 {
1514 {
1515 FunctionCallScope callScope(vm_);
1516 ASSERT_FALSE(vm_->IsTopLevelCallDepth());
1517 }
1518 ASSERT_TRUE(vm_->IsTopLevelCallDepth());
1519 }
1520 } // namespace panda::test
1521