forked from facebook/hermes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtestlib.cpp
More file actions
1428 lines (1235 loc) · 46.1 KB
/
testlib.cpp
File metadata and controls
1428 lines (1235 loc) · 46.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <jsi/test/testlib.h>
#include <gtest/gtest.h>
#include <jsi/decorator.h>
#include <jsi/jsi.h>
#include <stdlib.h>
#include <chrono>
#include <functional>
#include <thread>
#include <unordered_map>
#include <unordered_set>
using namespace facebook::jsi;
class JSITest : public JSITestBase {};
TEST_P(JSITest, RuntimeTest) {
auto v = rt.evaluateJavaScript(std::make_unique<StringBuffer>("1"), "");
EXPECT_EQ(v.getNumber(), 1);
rt.evaluateJavaScript(std::make_unique<StringBuffer>("x = 1"), "");
EXPECT_EQ(rt.global().getProperty(rt, "x").getNumber(), 1);
}
TEST_P(JSITest, PropNameIDTest) {
// This is a little weird to test, because it doesn't really exist
// in JS yet. All I can do is create them, compare them, and
// receive one as an argument to a HostObject.
PropNameID quux = PropNameID::forAscii(rt, "quux1", 4);
PropNameID movedQuux = std::move(quux);
EXPECT_EQ(movedQuux.utf8(rt), "quux");
movedQuux = PropNameID::forAscii(rt, "quux2");
EXPECT_EQ(movedQuux.utf8(rt), "quux2");
PropNameID copiedQuux = PropNameID(rt, movedQuux);
EXPECT_TRUE(PropNameID::compare(rt, movedQuux, copiedQuux));
EXPECT_TRUE(PropNameID::compare(rt, movedQuux, movedQuux));
EXPECT_TRUE(PropNameID::compare(
rt, movedQuux, PropNameID::forAscii(rt, std::string("quux2"))));
EXPECT_FALSE(PropNameID::compare(
rt, movedQuux, PropNameID::forAscii(rt, std::string("foo"))));
uint8_t utf8[] = {0xF0, 0x9F, 0x86, 0x97};
PropNameID utf8PropNameID = PropNameID::forUtf8(rt, utf8, sizeof(utf8));
EXPECT_EQ(utf8PropNameID.utf8(rt), u8"\U0001F197");
EXPECT_TRUE(PropNameID::compare(
rt, utf8PropNameID, PropNameID::forUtf8(rt, utf8, sizeof(utf8))));
PropNameID nonUtf8PropNameID = PropNameID::forUtf8(rt, "meow");
EXPECT_TRUE(PropNameID::compare(
rt, nonUtf8PropNameID, PropNameID::forAscii(rt, "meow")));
EXPECT_EQ(nonUtf8PropNameID.utf8(rt), "meow");
PropNameID strPropNameID =
PropNameID::forString(rt, String::createFromAscii(rt, "meow"));
EXPECT_TRUE(PropNameID::compare(rt, nonUtf8PropNameID, strPropNameID));
auto names = PropNameID::names(
rt, "Ala", std::string("ma"), PropNameID::forAscii(rt, "kota"));
EXPECT_EQ(names.size(), 3);
EXPECT_TRUE(
PropNameID::compare(rt, names[0], PropNameID::forAscii(rt, "Ala")));
EXPECT_TRUE(
PropNameID::compare(rt, names[1], PropNameID::forAscii(rt, "ma")));
EXPECT_TRUE(
PropNameID::compare(rt, names[2], PropNameID::forAscii(rt, "kota")));
}
TEST_P(JSITest, StringTest) {
EXPECT_TRUE(checkValue(String::createFromAscii(rt, "foobar", 3), "'foo'"));
EXPECT_TRUE(checkValue(String::createFromAscii(rt, "foobar"), "'foobar'"));
std::string baz = "baz";
EXPECT_TRUE(checkValue(String::createFromAscii(rt, baz), "'baz'"));
uint8_t utf8[] = {0xF0, 0x9F, 0x86, 0x97};
EXPECT_TRUE(checkValue(
String::createFromUtf8(rt, utf8, sizeof(utf8)), "'\\uD83C\\uDD97'"));
EXPECT_EQ(eval("'quux'").getString(rt).utf8(rt), "quux");
EXPECT_EQ(eval("'\\u20AC'").getString(rt).utf8(rt), "\xe2\x82\xac");
String quux = String::createFromAscii(rt, "quux");
String movedQuux = std::move(quux);
EXPECT_EQ(movedQuux.utf8(rt), "quux");
movedQuux = String::createFromAscii(rt, "quux2");
EXPECT_EQ(movedQuux.utf8(rt), "quux2");
}
TEST_P(JSITest, ObjectTest) {
eval("x = {1:2, '3':4, 5:'six', 'seven':['eight', 'nine']}");
Object x = rt.global().getPropertyAsObject(rt, "x");
EXPECT_EQ(x.getPropertyNames(rt).size(rt), 4);
EXPECT_TRUE(x.hasProperty(rt, "1"));
EXPECT_TRUE(x.hasProperty(rt, PropNameID::forAscii(rt, "1")));
EXPECT_FALSE(x.hasProperty(rt, "2"));
EXPECT_FALSE(x.hasProperty(rt, PropNameID::forAscii(rt, "2")));
EXPECT_TRUE(x.hasProperty(rt, "3"));
EXPECT_TRUE(x.hasProperty(rt, PropNameID::forAscii(rt, "3")));
EXPECT_TRUE(x.hasProperty(rt, "seven"));
EXPECT_TRUE(x.hasProperty(rt, PropNameID::forAscii(rt, "seven")));
EXPECT_EQ(x.getProperty(rt, "1").getNumber(), 2);
EXPECT_EQ(x.getProperty(rt, PropNameID::forAscii(rt, "1")).getNumber(), 2);
EXPECT_EQ(x.getProperty(rt, "3").getNumber(), 4);
Value five = 5;
EXPECT_EQ(
x.getProperty(rt, PropNameID::forString(rt, five.toString(rt)))
.getString(rt)
.utf8(rt),
"six");
x.setProperty(rt, "ten", 11);
EXPECT_EQ(x.getPropertyNames(rt).size(rt), 5);
EXPECT_TRUE(eval("x.ten == 11").getBool());
x.setProperty(rt, "e_as_float", 2.71f);
EXPECT_TRUE(eval("Math.abs(x.e_as_float - 2.71) < 0.001").getBool());
x.setProperty(rt, "e_as_double", 2.71);
EXPECT_TRUE(eval("x.e_as_double == 2.71").getBool());
uint8_t utf8[] = {0xF0, 0x9F, 0x86, 0x97};
String nonAsciiName = String::createFromUtf8(rt, utf8, sizeof(utf8));
x.setProperty(rt, PropNameID::forString(rt, nonAsciiName), "emoji");
EXPECT_EQ(x.getPropertyNames(rt).size(rt), 8);
EXPECT_TRUE(eval("x['\\uD83C\\uDD97'] == 'emoji'").getBool());
Object seven = x.getPropertyAsObject(rt, "seven");
EXPECT_TRUE(seven.isArray(rt));
Object evalf = rt.global().getPropertyAsObject(rt, "eval");
EXPECT_TRUE(evalf.isFunction(rt));
Object movedX = Object(rt);
movedX = std::move(x);
EXPECT_EQ(movedX.getPropertyNames(rt).size(rt), 8);
EXPECT_EQ(movedX.getProperty(rt, "1").getNumber(), 2);
Object obj = Object(rt);
obj.setProperty(rt, "roses", "red");
obj.setProperty(rt, "violets", "blue");
Object oprop = Object(rt);
obj.setProperty(rt, "oprop", oprop);
obj.setProperty(rt, "aprop", Array(rt, 1));
EXPECT_TRUE(function("function (obj) { return "
"obj.roses == 'red' && "
"obj['violets'] == 'blue' && "
"typeof obj.oprop == 'object' && "
"Array.isArray(obj.aprop); }")
.call(rt, obj)
.getBool());
// Check that getPropertyNames doesn't return non-enumerable
// properties.
obj = function(
"function () {"
" obj = {};"
" obj.a = 1;"
" Object.defineProperty(obj, 'b', {"
" enumerable: false,"
" value: 2"
" });"
" return obj;"
"}")
.call(rt)
.getObject(rt);
EXPECT_EQ(obj.getProperty(rt, "a").getNumber(), 1);
EXPECT_EQ(obj.getProperty(rt, "b").getNumber(), 2);
Array names = obj.getPropertyNames(rt);
EXPECT_EQ(names.size(rt), 1);
EXPECT_EQ(names.getValueAtIndex(rt, 0).getString(rt).utf8(rt), "a");
}
TEST_P(JSITest, HostObjectTest) {
class ConstantHostObject : public HostObject {
Value get(Runtime&, const PropNameID& sym) override {
return 9000;
}
void set(Runtime&, const PropNameID&, const Value&) override {}
};
Object cho =
Object::createFromHostObject(rt, std::make_shared<ConstantHostObject>());
EXPECT_TRUE(function("function (obj) { return obj.someRandomProp == 9000; }")
.call(rt, cho)
.getBool());
EXPECT_TRUE(cho.isHostObject(rt));
EXPECT_TRUE(cho.getHostObject<ConstantHostObject>(rt).get() != nullptr);
struct SameRuntimeHostObject : HostObject {
SameRuntimeHostObject(Runtime& rt) : rt_(rt){};
Value get(Runtime& rt, const PropNameID& sym) override {
EXPECT_EQ(&rt, &rt_);
return Value();
}
void set(Runtime& rt, const PropNameID& name, const Value& value) override {
EXPECT_EQ(&rt, &rt_);
}
std::vector<PropNameID> getPropertyNames(Runtime& rt) override {
EXPECT_EQ(&rt, &rt_);
return {};
}
Runtime& rt_;
};
Object srho = Object::createFromHostObject(
rt, std::make_shared<SameRuntimeHostObject>(rt));
// Test get's Runtime is as expected
function("function (obj) { return obj.isSame; }").call(rt, srho);
// ... and set
function("function (obj) { obj['k'] = 'v'; }").call(rt, srho);
// ... and getPropertyNames
function("function (obj) { for (k in obj) {} }").call(rt, srho);
class TwiceHostObject : public HostObject {
Value get(Runtime& rt, const PropNameID& sym) override {
return String::createFromUtf8(rt, sym.utf8(rt) + sym.utf8(rt));
}
void set(Runtime&, const PropNameID&, const Value&) override {}
};
Object tho =
Object::createFromHostObject(rt, std::make_shared<TwiceHostObject>());
EXPECT_TRUE(function("function (obj) { return obj.abc == 'abcabc'; }")
.call(rt, tho)
.getBool());
EXPECT_TRUE(function("function (obj) { return obj['def'] == 'defdef'; }")
.call(rt, tho)
.getBool());
EXPECT_TRUE(function("function (obj) { return obj[12] === '1212'; }")
.call(rt, tho)
.getBool());
EXPECT_TRUE(tho.isHostObject(rt));
EXPECT_TRUE(
std::dynamic_pointer_cast<ConstantHostObject>(tho.getHostObject(rt)) ==
nullptr);
EXPECT_TRUE(tho.getHostObject<TwiceHostObject>(rt).get() != nullptr);
class PropNameIDHostObject : public HostObject {
Value get(Runtime& rt, const PropNameID& sym) override {
if (PropNameID::compare(rt, sym, PropNameID::forAscii(rt, "undef"))) {
return Value::undefined();
} else {
return PropNameID::compare(
rt, sym, PropNameID::forAscii(rt, "somesymbol"));
}
}
void set(Runtime&, const PropNameID&, const Value&) override {}
};
Object sho = Object::createFromHostObject(
rt, std::make_shared<PropNameIDHostObject>());
EXPECT_TRUE(sho.isHostObject(rt));
EXPECT_TRUE(function("function (obj) { return obj.undef; }")
.call(rt, sho)
.isUndefined());
EXPECT_TRUE(function("function (obj) { return obj.somesymbol; }")
.call(rt, sho)
.getBool());
EXPECT_FALSE(function("function (obj) { return obj.notsomuch; }")
.call(rt, sho)
.getBool());
class BagHostObject : public HostObject {
public:
const std::string& getThing() {
return bag_["thing"];
}
private:
Value get(Runtime& rt, const PropNameID& sym) override {
if (sym.utf8(rt) == "thing") {
return String::createFromUtf8(rt, bag_[sym.utf8(rt)]);
}
return Value::undefined();
}
void set(Runtime& rt, const PropNameID& sym, const Value& val) override {
std::string key(sym.utf8(rt));
if (key == "thing") {
bag_[key] = val.toString(rt).utf8(rt);
}
}
std::unordered_map<std::string, std::string> bag_;
};
std::shared_ptr<BagHostObject> shbho = std::make_shared<BagHostObject>();
Object bho = Object::createFromHostObject(rt, shbho);
EXPECT_TRUE(bho.isHostObject(rt));
EXPECT_TRUE(function("function (obj) { return obj.undef; }")
.call(rt, bho)
.isUndefined());
EXPECT_EQ(
function("function (obj) { obj.thing = 'hello'; return obj.thing; }")
.call(rt, bho)
.toString(rt)
.utf8(rt),
"hello");
EXPECT_EQ(shbho->getThing(), "hello");
class ThrowingHostObject : public HostObject {
Value get(Runtime& rt, const PropNameID& sym) override {
throw std::runtime_error("Cannot get");
}
void set(Runtime& rt, const PropNameID& sym, const Value& val) override {
throw std::runtime_error("Cannot set");
}
};
Object thro =
Object::createFromHostObject(rt, std::make_shared<ThrowingHostObject>());
EXPECT_TRUE(thro.isHostObject(rt));
std::string exc;
try {
function("function (obj) { return obj.thing; }").call(rt, thro);
} catch (const JSError& ex) {
exc = ex.what();
}
EXPECT_NE(exc.find("Cannot get"), std::string::npos);
exc = "";
try {
function("function (obj) { obj.thing = 'hello'; }").call(rt, thro);
} catch (const JSError& ex) {
exc = ex.what();
}
EXPECT_NE(exc.find("Cannot set"), std::string::npos);
class NopHostObject : public HostObject {};
Object nopHo =
Object::createFromHostObject(rt, std::make_shared<NopHostObject>());
EXPECT_TRUE(nopHo.isHostObject(rt));
EXPECT_TRUE(function("function (obj) { return obj.thing; }")
.call(rt, nopHo)
.isUndefined());
std::string nopExc;
try {
function("function (obj) { obj.thing = 'pika'; }").call(rt, nopHo);
} catch (const JSError& ex) {
nopExc = ex.what();
}
EXPECT_NE(nopExc.find("TypeError: "), std::string::npos);
class HostObjectWithPropertyNames : public HostObject {
std::vector<PropNameID> getPropertyNames(Runtime& rt) override {
return PropNameID::names(
rt, "a_prop", "1", "false", "a_prop", "3", "c_prop");
}
};
Object howpn = Object::createFromHostObject(
rt, std::make_shared<HostObjectWithPropertyNames>());
EXPECT_TRUE(
function(
"function (o) { return Object.getOwnPropertyNames(o).length == 5 }")
.call(rt, howpn)
.getBool());
auto hasOwnPropertyName = function(
"function (o, p) {"
" return Object.getOwnPropertyNames(o).indexOf(p) >= 0"
"}");
EXPECT_TRUE(
hasOwnPropertyName.call(rt, howpn, String::createFromAscii(rt, "a_prop"))
.getBool());
EXPECT_TRUE(
hasOwnPropertyName.call(rt, howpn, String::createFromAscii(rt, "1"))
.getBool());
EXPECT_TRUE(
hasOwnPropertyName.call(rt, howpn, String::createFromAscii(rt, "false"))
.getBool());
EXPECT_TRUE(
hasOwnPropertyName.call(rt, howpn, String::createFromAscii(rt, "3"))
.getBool());
EXPECT_TRUE(
hasOwnPropertyName.call(rt, howpn, String::createFromAscii(rt, "c_prop"))
.getBool());
EXPECT_FALSE(hasOwnPropertyName
.call(rt, howpn, String::createFromAscii(rt, "not_existing"))
.getBool());
}
TEST_P(JSITest, HostObjectProtoTest) {
class ProtoHostObject : public HostObject {
Value get(Runtime& rt, const PropNameID&) override {
return String::createFromAscii(rt, "phoprop");
}
};
rt.global().setProperty(
rt,
"pho",
Object::createFromHostObject(rt, std::make_shared<ProtoHostObject>()));
EXPECT_EQ(
eval("({__proto__: pho})[Symbol.toPrimitive]").getString(rt).utf8(rt),
"phoprop");
}
TEST_P(JSITest, ArrayTest) {
eval("x = {1:2, '3':4, 5:'six', 'seven':['eight', 'nine']}");
Object x = rt.global().getPropertyAsObject(rt, "x");
Array names = x.getPropertyNames(rt);
EXPECT_EQ(names.size(rt), 4);
std::unordered_set<std::string> strNames;
for (size_t i = 0; i < names.size(rt); ++i) {
Value n = names.getValueAtIndex(rt, i);
EXPECT_TRUE(n.isString());
strNames.insert(n.getString(rt).utf8(rt));
}
EXPECT_EQ(strNames.size(), 4);
EXPECT_EQ(strNames.count("1"), 1);
EXPECT_EQ(strNames.count("3"), 1);
EXPECT_EQ(strNames.count("5"), 1);
EXPECT_EQ(strNames.count("seven"), 1);
Object seven = x.getPropertyAsObject(rt, "seven");
Array arr = seven.getArray(rt);
EXPECT_EQ(arr.size(rt), 2);
EXPECT_EQ(arr.getValueAtIndex(rt, 0).getString(rt).utf8(rt), "eight");
EXPECT_EQ(arr.getValueAtIndex(rt, 1).getString(rt).utf8(rt), "nine");
// TODO: test out of range
EXPECT_EQ(x.getPropertyAsObject(rt, "seven").getArray(rt).size(rt), 2);
// Check that property access with both symbols and strings can access
// array values.
EXPECT_EQ(seven.getProperty(rt, "0").getString(rt).utf8(rt), "eight");
EXPECT_EQ(seven.getProperty(rt, "1").getString(rt).utf8(rt), "nine");
seven.setProperty(rt, "1", "modified");
EXPECT_EQ(seven.getProperty(rt, "1").getString(rt).utf8(rt), "modified");
EXPECT_EQ(arr.getValueAtIndex(rt, 1).getString(rt).utf8(rt), "modified");
EXPECT_EQ(
seven.getProperty(rt, PropNameID::forAscii(rt, "0"))
.getString(rt)
.utf8(rt),
"eight");
seven.setProperty(rt, PropNameID::forAscii(rt, "0"), "modified2");
EXPECT_EQ(arr.getValueAtIndex(rt, 0).getString(rt).utf8(rt), "modified2");
Array alpha = Array(rt, 4);
EXPECT_TRUE(alpha.getValueAtIndex(rt, 0).isUndefined());
EXPECT_TRUE(alpha.getValueAtIndex(rt, 3).isUndefined());
EXPECT_EQ(alpha.size(rt), 4);
alpha.setValueAtIndex(rt, 0, "a");
alpha.setValueAtIndex(rt, 1, "b");
EXPECT_EQ(alpha.length(rt), 4);
alpha.setValueAtIndex(rt, 2, "c");
alpha.setValueAtIndex(rt, 3, "d");
EXPECT_EQ(alpha.size(rt), 4);
EXPECT_TRUE(
function(
"function (arr) { return "
"arr.length == 4 && "
"['a','b','c','d'].every(function(v,i) { return v === arr[i]}); }")
.call(rt, alpha)
.getBool());
Array alpha2 = Array(rt, 1);
alpha2 = std::move(alpha);
EXPECT_EQ(alpha2.size(rt), 4);
}
TEST_P(JSITest, FunctionTest) {
// test move ctor
Function fmove = function("function() { return 1 }");
{
Function g = function("function() { return 2 }");
fmove = std::move(g);
}
EXPECT_EQ(fmove.call(rt).getNumber(), 2);
// This tests all the function argument converters, and all the
// non-lvalue overloads of call().
Function f = function(
"function(n, b, d, df, i, s1, s2, s3, s_sun, s_bad, o, a, f, v) { "
"return "
"n === null && "
"b === true && "
"d === 3.14 && "
"Math.abs(df - 2.71) < 0.001 && "
"i === 17 && "
"s1 == 's1' && "
"s2 == 's2' && "
"s3 == 's3' && "
"s_sun == 's\\u2600' && "
"typeof s_bad == 'string' && "
"typeof o == 'object' && "
"Array.isArray(a) && "
"typeof f == 'function' && "
"v == 42 }");
EXPECT_TRUE(f.call(
rt,
nullptr,
true,
3.14,
2.71f,
17,
"s1",
String::createFromAscii(rt, "s2"),
std::string{"s3"},
std::string{u8"s\u2600"},
// invalid UTF8 sequence due to unexpected continuation byte
std::string{"s\x80"},
Object(rt),
Array(rt, 1),
function("function(){}"),
Value(42))
.getBool());
// lvalue overloads of call()
Function flv = function(
"function(s, o, a, f, v) { return "
"s == 's' && "
"typeof o == 'object' && "
"Array.isArray(a) && "
"typeof f == 'function' && "
"v == 42 }");
String s = String::createFromAscii(rt, "s");
Object o = Object(rt);
Array a = Array(rt, 1);
Value v = 42;
EXPECT_TRUE(flv.call(rt, s, o, a, f, v).getBool());
Function f1 = function("function() { return 1; }");
Function f2 = function("function() { return 2; }");
f2 = std::move(f1);
EXPECT_EQ(f2.call(rt).getNumber(), 1);
}
TEST_P(JSITest, FunctionThisTest) {
Function checkPropertyFunction =
function("function() { return this.a === 'a_property' }");
Object jsObject = Object(rt);
jsObject.setProperty(rt, "a", String::createFromUtf8(rt, "a_property"));
class APropertyHostObject : public HostObject {
Value get(Runtime& rt, const PropNameID& sym) override {
return String::createFromUtf8(rt, "a_property");
}
void set(Runtime&, const PropNameID&, const Value&) override {}
};
Object hostObject =
Object::createFromHostObject(rt, std::make_shared<APropertyHostObject>());
EXPECT_TRUE(checkPropertyFunction.callWithThis(rt, jsObject).getBool());
EXPECT_TRUE(checkPropertyFunction.callWithThis(rt, hostObject).getBool());
EXPECT_FALSE(checkPropertyFunction.callWithThis(rt, Array(rt, 5)).getBool());
EXPECT_FALSE(checkPropertyFunction.call(rt).getBool());
}
TEST_P(JSITest, FunctionConstructorTest) {
Function ctor = function(
"function (a) {"
" if (typeof a !== 'undefined') {"
" this.pika = a;"
" }"
"}");
ctor.getProperty(rt, "prototype")
.getObject(rt)
.setProperty(rt, "pika", "chu");
auto empty = ctor.callAsConstructor(rt);
EXPECT_TRUE(empty.isObject());
auto emptyObj = std::move(empty).getObject(rt);
EXPECT_EQ(emptyObj.getProperty(rt, "pika").getString(rt).utf8(rt), "chu");
auto who = ctor.callAsConstructor(rt, "who");
EXPECT_TRUE(who.isObject());
auto whoObj = std::move(who).getObject(rt);
EXPECT_EQ(whoObj.getProperty(rt, "pika").getString(rt).utf8(rt), "who");
auto instanceof = function("function (o, b) { return o instanceof b; }");
EXPECT_TRUE(instanceof.call(rt, emptyObj, ctor).getBool());
EXPECT_TRUE(instanceof.call(rt, whoObj, ctor).getBool());
auto dateCtor = rt.global().getPropertyAsFunction(rt, "Date");
auto date = dateCtor.callAsConstructor(rt);
EXPECT_TRUE(date.isObject());
EXPECT_TRUE(instanceof.call(rt, date, dateCtor).getBool());
// Sleep for 50 milliseconds
std::this_thread::sleep_for(std::chrono::milliseconds(50));
EXPECT_GE(
function("function (d) { return (new Date()).getTime() - d.getTime(); }")
.call(rt, date)
.getNumber(),
50);
}
TEST_P(JSITest, InstanceOfTest) {
auto ctor = function("function Rick() { this.say = 'wubalubadubdub'; }");
auto newObj = function("function (ctor) { return new ctor(); }");
auto instance = newObj.call(rt, ctor).getObject(rt);
EXPECT_TRUE(instance.instanceOf(rt, ctor));
EXPECT_EQ(
instance.getProperty(rt, "say").getString(rt).utf8(rt), "wubalubadubdub");
EXPECT_FALSE(Object(rt).instanceOf(rt, ctor));
EXPECT_TRUE(ctor.callAsConstructor(rt, nullptr, 0)
.getObject(rt)
.instanceOf(rt, ctor));
}
TEST_P(JSITest, HostFunctionTest) {
auto one = std::make_shared<int>(1);
Function plusOne = Function::createFromHostFunction(
rt,
PropNameID::forAscii(rt, "plusOne"),
2,
[one, savedRt = &rt](
Runtime& rt, const Value& thisVal, const Value* args, size_t count) {
EXPECT_EQ(savedRt, &rt);
// We don't know if we're in strict mode or not, so it's either global
// or undefined.
EXPECT_TRUE(
Value::strictEquals(rt, thisVal, rt.global()) ||
thisVal.isUndefined());
return *one + args[0].getNumber() + args[1].getNumber();
});
EXPECT_EQ(plusOne.call(rt, 1, 2).getNumber(), 4);
EXPECT_TRUE(checkValue(plusOne.call(rt, 3, 5), "9"));
rt.global().setProperty(rt, "plusOne", plusOne);
EXPECT_TRUE(eval("plusOne(20, 300) == 321").getBool());
Function dot = Function::createFromHostFunction(
rt,
PropNameID::forAscii(rt, "dot"),
2,
[](Runtime& rt, const Value& thisVal, const Value* args, size_t count) {
EXPECT_TRUE(
Value::strictEquals(rt, thisVal, rt.global()) ||
thisVal.isUndefined());
if (count != 2) {
throw std::runtime_error("expected 2 args");
}
std::string ret = args[0].getString(rt).utf8(rt) + "." +
args[1].getString(rt).utf8(rt);
return String::createFromUtf8(
rt, reinterpret_cast<const uint8_t*>(ret.data()), ret.size());
});
rt.global().setProperty(rt, "cons", dot);
EXPECT_TRUE(eval("cons('left', 'right') == 'left.right'").getBool());
EXPECT_TRUE(eval("cons.name == 'dot'").getBool());
EXPECT_TRUE(eval("cons.length == 2").getBool());
EXPECT_TRUE(eval("cons instanceof Function").getBool());
EXPECT_TRUE(eval("(function() {"
" try {"
" cons('fail'); return false;"
" } catch (e) {"
" return ((e instanceof Error) &&"
" (e.message == 'Exception in HostFunction: ' +"
" 'expected 2 args'));"
" }})()")
.getBool());
Function coolify = Function::createFromHostFunction(
rt,
PropNameID::forAscii(rt, "coolify"),
0,
[](Runtime& rt, const Value& thisVal, const Value* args, size_t count) {
EXPECT_EQ(count, 0);
std::string ret = thisVal.toString(rt).utf8(rt) + " is cool";
return String::createFromUtf8(
rt, reinterpret_cast<const uint8_t*>(ret.data()), ret.size());
});
rt.global().setProperty(rt, "coolify", coolify);
EXPECT_TRUE(eval("coolify.name == 'coolify'").getBool());
EXPECT_TRUE(eval("coolify.length == 0").getBool());
EXPECT_TRUE(eval("coolify.bind('R&M')() == 'R&M is cool'").getBool());
EXPECT_TRUE(eval("(function() {"
" var s = coolify.bind(function(){})();"
" return s.lastIndexOf(' is cool') == (s.length - 8);"
"})()")
.getBool());
Function lookAtMe = Function::createFromHostFunction(
rt,
PropNameID::forAscii(rt, "lookAtMe"),
0,
[](Runtime& rt, const Value& thisVal, const Value* args, size_t count)
-> Value {
EXPECT_TRUE(thisVal.isObject());
EXPECT_EQ(
thisVal.getObject(rt)
.getProperty(rt, "name")
.getString(rt)
.utf8(rt),
"mr.meeseeks");
return Value();
});
rt.global().setProperty(rt, "lookAtMe", lookAtMe);
EXPECT_TRUE(eval("lookAtMe.bind({'name': 'mr.meeseeks'})()").isUndefined());
struct Callable {
Callable(std::string s) : str(s) {}
Value
operator()(Runtime& rt, const Value&, const Value* args, size_t count) {
if (count != 1) {
return Value();
}
return String::createFromUtf8(
rt, args[0].toString(rt).utf8(rt) + " was called with " + str);
}
std::string str;
};
Function callable = Function::createFromHostFunction(
rt,
PropNameID::forAscii(rt, "callable"),
1,
Callable("std::function::target"));
EXPECT_EQ(
function("function (f) { return f('A cat'); }")
.call(rt, callable)
.getString(rt)
.utf8(rt),
"A cat was called with std::function::target");
EXPECT_TRUE(callable.isHostFunction(rt));
EXPECT_NE(callable.getHostFunction(rt).target<Callable>(), nullptr);
std::string strval = "strval1";
auto getter = Object(rt);
getter.setProperty(
rt,
"get",
Function::createFromHostFunction(
rt,
PropNameID::forAscii(rt, "getter"),
1,
[&strval](
Runtime& rt,
const Value& thisVal,
const Value* args,
size_t count) -> Value {
return String::createFromUtf8(rt, strval);
}));
auto obj = Object(rt);
rt.global()
.getPropertyAsObject(rt, "Object")
.getPropertyAsFunction(rt, "defineProperty")
.call(rt, obj, "prop", getter);
EXPECT_TRUE(function("function(value) { return value.prop == 'strval1'; }")
.call(rt, obj)
.getBool());
strval = "strval2";
EXPECT_TRUE(function("function(value) { return value.prop == 'strval2'; }")
.call(rt, obj)
.getBool());
}
TEST_P(JSITest, ValueTest) {
EXPECT_TRUE(checkValue(Value::undefined(), "undefined"));
EXPECT_TRUE(checkValue(Value(), "undefined"));
EXPECT_TRUE(checkValue(Value::null(), "null"));
EXPECT_TRUE(checkValue(nullptr, "null"));
EXPECT_TRUE(checkValue(Value(false), "false"));
EXPECT_TRUE(checkValue(false, "false"));
EXPECT_TRUE(checkValue(true, "true"));
EXPECT_TRUE(checkValue(Value(1.5), "1.5"));
EXPECT_TRUE(checkValue(2.5, "2.5"));
EXPECT_TRUE(checkValue(Value(10), "10"));
EXPECT_TRUE(checkValue(20, "20"));
EXPECT_TRUE(checkValue(30, "30"));
// rvalue implicit conversion
EXPECT_TRUE(checkValue(String::createFromAscii(rt, "one"), "'one'"));
// lvalue explicit copy
String s = String::createFromAscii(rt, "two");
EXPECT_TRUE(checkValue(Value(rt, s), "'two'"));
{
// rvalue assignment of trivial value
Value v1 = 100;
Value v2 = String::createFromAscii(rt, "hundred");
v2 = std::move(v1);
EXPECT_TRUE(v2.isNumber());
EXPECT_EQ(v2.getNumber(), 100);
}
{
// rvalue assignment of js heap value
Value v1 = String::createFromAscii(rt, "hundred");
Value v2 = 100;
v2 = std::move(v1);
EXPECT_TRUE(v2.isString());
EXPECT_EQ(v2.getString(rt).utf8(rt), "hundred");
}
Object o = Object(rt);
EXPECT_TRUE(function("function(value) { return typeof(value) == 'object'; }")
.call(rt, Value(rt, o))
.getBool());
uint8_t utf8[] = "[null, 2, \"c\", \"emoji: \xf0\x9f\x86\x97\", {}]";
EXPECT_TRUE(
function("function (arr) { return "
"Array.isArray(arr) && "
"arr.length == 5 && "
"arr[0] === null && "
"arr[1] == 2 && "
"arr[2] == 'c' && "
"arr[3] == 'emoji: \\uD83C\\uDD97' && "
"typeof arr[4] == 'object'; }")
.call(rt, Value::createFromJsonUtf8(rt, utf8, sizeof(utf8) - 1))
.getBool());
EXPECT_TRUE(eval("undefined").isUndefined());
EXPECT_TRUE(eval("null").isNull());
EXPECT_TRUE(eval("true").isBool());
EXPECT_TRUE(eval("false").isBool());
EXPECT_TRUE(eval("123").isNumber());
EXPECT_TRUE(eval("123.4").isNumber());
EXPECT_TRUE(eval("'str'").isString());
// "{}" returns undefined. empty code block?
EXPECT_TRUE(eval("({})").isObject());
EXPECT_TRUE(eval("[]").isObject());
EXPECT_TRUE(eval("(function(){})").isObject());
EXPECT_EQ(eval("123").getNumber(), 123);
EXPECT_EQ(eval("123.4").getNumber(), 123.4);
EXPECT_EQ(eval("'str'").getString(rt).utf8(rt), "str");
EXPECT_TRUE(eval("[]").getObject(rt).isArray(rt));
EXPECT_EQ(eval("456").asNumber(), 456);
EXPECT_THROW(eval("'word'").asNumber(), JSIException);
EXPECT_EQ(
eval("({1:2, 3:4})").asObject(rt).getProperty(rt, "1").getNumber(), 2);
EXPECT_THROW(eval("'oops'").asObject(rt), JSIException);
EXPECT_EQ(eval("['zero',1,2,3]").toString(rt).utf8(rt), "zero,1,2,3");
}
TEST_P(JSITest, EqualsTest) {
EXPECT_TRUE(Object::strictEquals(rt, rt.global(), rt.global()));
EXPECT_TRUE(Value::strictEquals(rt, 1, 1));
EXPECT_FALSE(Value::strictEquals(rt, true, 1));
EXPECT_FALSE(Value::strictEquals(rt, true, false));
EXPECT_TRUE(Value::strictEquals(rt, false, false));
EXPECT_FALSE(Value::strictEquals(rt, nullptr, 1));
EXPECT_TRUE(Value::strictEquals(rt, nullptr, nullptr));
EXPECT_TRUE(Value::strictEquals(rt, Value::undefined(), Value()));
EXPECT_TRUE(Value::strictEquals(rt, rt.global(), Value(rt.global())));
EXPECT_FALSE(Value::strictEquals(
rt,
std::numeric_limits<double>::quiet_NaN(),
std::numeric_limits<double>::quiet_NaN()));
EXPECT_FALSE(Value::strictEquals(
rt,
std::numeric_limits<double>::signaling_NaN(),
std::numeric_limits<double>::signaling_NaN()));
EXPECT_TRUE(Value::strictEquals(rt, +0.0, -0.0));
EXPECT_TRUE(Value::strictEquals(rt, -0.0, +0.0));
Function noop = Function::createFromHostFunction(
rt,
PropNameID::forAscii(rt, "noop"),
0,
[](const Runtime&, const Value&, const Value*, size_t) {
return Value();
});
auto noopDup = Value(rt, noop).getObject(rt);
EXPECT_TRUE(Object::strictEquals(rt, noop, noopDup));
EXPECT_TRUE(Object::strictEquals(rt, noopDup, noop));
EXPECT_FALSE(Object::strictEquals(rt, noop, rt.global()));
EXPECT_TRUE(Object::strictEquals(rt, noop, noop));
EXPECT_TRUE(Value::strictEquals(rt, Value(rt, noop), Value(rt, noop)));
String str = String::createFromAscii(rt, "rick");
String strDup = String::createFromAscii(rt, "rick");
String otherStr = String::createFromAscii(rt, "morty");
EXPECT_TRUE(String::strictEquals(rt, str, str));
EXPECT_TRUE(String::strictEquals(rt, str, strDup));
EXPECT_TRUE(String::strictEquals(rt, strDup, str));
EXPECT_FALSE(String::strictEquals(rt, str, otherStr));
EXPECT_TRUE(Value::strictEquals(rt, Value(rt, str), Value(rt, str)));
EXPECT_FALSE(Value::strictEquals(rt, Value(rt, str), Value(rt, noop)));
EXPECT_FALSE(Value::strictEquals(rt, Value(rt, str), 1.0));
}
TEST_P(JSITest, ExceptionStackTraceTest) {
static const char invokeUndefinedScript[] =
"function hello() {"
" var a = {}; a.log(); }"
"function world() { hello(); }"
"world()";
std::string stack;
try {
rt.evaluateJavaScript(
std::make_unique<StringBuffer>(invokeUndefinedScript), "");
} catch (JSError& e) {
stack = e.getStack();
}
EXPECT_NE(stack.find("world"), std::string::npos);
}
TEST_P(JSITest, PreparedJavaScriptSourceTest) {
rt.evaluateJavaScript(std::make_unique<StringBuffer>("var q = 0;"), "");
auto prep = rt.prepareJavaScript(std::make_unique<StringBuffer>("q++;"), "");
EXPECT_EQ(rt.global().getProperty(rt, "q").getNumber(), 0);
rt.evaluatePreparedJavaScript(prep);
EXPECT_EQ(rt.global().getProperty(rt, "q").getNumber(), 1);
rt.evaluatePreparedJavaScript(prep);
EXPECT_EQ(rt.global().getProperty(rt, "q").getNumber(), 2);
}
TEST_P(JSITest, PreparedJavaScriptURLInBacktrace) {
std::string sourceURL = "//PreparedJavaScriptURLInBacktrace/Test/URL";
std::string throwingSource =
"function thrower() { throw new Error('oops')}"
"thrower();";
auto prep = rt.prepareJavaScript(
std::make_unique<StringBuffer>(throwingSource), sourceURL);
try {
rt.evaluatePreparedJavaScript(prep);
FAIL() << "prepareJavaScript should have thrown an exception";
} catch (facebook::jsi::JSError err) {
EXPECT_NE(std::string::npos, err.getStack().find(sourceURL))
<< "Backtrace should contain source URL";
}
}
namespace {
unsigned countOccurences(const std::string& of, const std::string& in) {
unsigned occurences = 0;
std::string::size_type lastOccurence = -1;
while ((lastOccurence = in.find(of, lastOccurence + 1)) !=
std::string::npos) {
occurences++;
}
return occurences;
}
} // namespace
TEST_P(JSITest, JSErrorsArePropagatedNicely) {
unsigned callsBeforeError = 5;
Function sometimesThrows = function(
"function sometimesThrows(shouldThrow, callback) {"
" if (shouldThrow) {"
" throw Error('Omg, what a nasty exception')"
" }"
" callback(callback);"
"}");
Function callback = Function::createFromHostFunction(
rt,
PropNameID::forAscii(rt, "callback"),
0,
[&sometimesThrows, &callsBeforeError](
Runtime& rt, const Value& thisVal, const Value* args, size_t count) {
return sometimesThrows.call(rt, --callsBeforeError == 0, args[0]);
});
try {
sometimesThrows.call(rt, false, callback);
} catch (JSError& error) {
EXPECT_EQ(error.getMessage(), "Omg, what a nasty exception");
EXPECT_EQ(countOccurences("sometimesThrows", error.getStack()), 6);
// system JSC JSI does not implement host function names
// EXPECT_EQ(countOccurences("callback", error.getStack(rt)), 5);
}
}
TEST_P(JSITest, JSErrorsCanBeConstructedWithStack) {
auto err = JSError(rt, "message", "stack");
EXPECT_EQ(err.getMessage(), "message");
EXPECT_EQ(err.getStack(), "stack");
}
TEST_P(JSITest, JSErrorDoesNotInfinitelyRecurse) {