-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathQuickJSContextTest.java
More file actions
953 lines (847 loc) · 34.5 KB
/
Copy pathQuickJSContextTest.java
File metadata and controls
953 lines (847 loc) · 34.5 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
package io.github.stefanrichterhuber.quickjswasmjava;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.jupiter.api.Test;
public class QuickJSContextTest {
private static final Logger LOGGER = LogManager.getLogger();
/**
* All supported java types can be returned from the eval function
*
* @throws Exception
*/
@Test
public void testReturnValuesFromEval() throws Exception {
try (QuickJSRuntime runtime = new QuickJSRuntime();
QuickJSContext context = runtime.createContext()) {
// Test return of null
{
Object result = context.eval("let ra = null; ra");
assertEquals(null, result);
}
// Test return of undefined
{
Object result = context.eval("let rb = undefined; rb");
assertEquals(null, result);
}
// Test return of integer
{
Object result = context.eval("3 + 1");
assertInstanceOf(Integer.class, result);
assertEquals(4, result);
}
// Test return of string
{
Object result = context.eval(" 'Hello ' + 'World'");
assertInstanceOf(String.class, result);
assertEquals("Hello World", result);
}
// Test return of boolean
{
Object result = context.eval(" true");
assertInstanceOf(Boolean.class, result);
assertEquals(true, result);
}
// Test return of double
{
Object result = context.eval(" 3.14");
assertInstanceOf(Double.class, result);
assertEquals(3.14, result);
}
// Test return of (heterogeneous and nested) array
{
Object result = context.eval("[ 3.14, 42, 'hello', true, [1,2,3]]");
assertInstanceOf(List.class, result);
@SuppressWarnings("unchecked")
List<Object> list = (List<Object>) result;
assertEquals(5, list.size());
assertEquals(3.14, list.get(0));
assertEquals(42, list.get(1));
assertEquals("hello", list.get(2));
assertEquals(true, list.get(3));
assertInstanceOf(List.class, list.get(4));
@SuppressWarnings("unchecked")
List<Object> nestedList = (List<Object>) list.get(4);
assertEquals(3, nestedList.size());
assertEquals(1, nestedList.get(0));
assertEquals(2, nestedList.get(1));
assertEquals(3, nestedList.get(2));
}
// Test return of (heterogeneous and nested) object
{
Object result = context
.eval("let r = { a: 3.14, b: 42, c: 'hello', d: true, e: [1,2,3], f: {g: 42}}; r");
assertInstanceOf(Map.class, result);
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) result;
assertEquals(6, map.size());
assertEquals(3.14, map.get("a"));
assertEquals(42, map.get("b"));
assertEquals("hello", map.get("c"));
assertEquals(true, map.get("d"));
assertInstanceOf(List.class, map.get("e"));
@SuppressWarnings("unchecked")
List<Object> nestedList = (List<Object>) map.get("e");
assertEquals(3, nestedList.size());
assertEquals(1, nestedList.get(0));
assertEquals(2, nestedList.get(1));
assertEquals(3, nestedList.get(2));
assertInstanceOf(Map.class, map.get("f"));
@SuppressWarnings("unchecked")
Map<String, Object> nestedMap = (Map<String, Object>) map.get("f");
assertEquals(1, nestedMap.size());
assertEquals(42, nestedMap.get("g"));
}
}
}
/**
* Even functions can be returned form the eval function and will be represented
* as QuickJSFunction in java
*
* @throws Exception
*/
@Test
public void testReturnFunctionFromEval() throws Exception {
try (QuickJSRuntime runtime = new QuickJSRuntime();
QuickJSContext context = runtime.createContext()) {
// Local function
{
Object result = context.eval("let r = function() { return 42; }; r");
assertInstanceOf(QuickJSFunction.class, result);
QuickJSFunction function = (QuickJSFunction) result;
assertEquals(42, function.call());
assertEquals(42, function.call());
assertEquals(42, function.call());
assertEquals(42, function.call());
// QuickJSFunction implements java.util.function.Function<List<Object>, Object>
assertEquals(42, function.apply(List.of()));
// JS Function can be added back to the js context with a different name
context.setGlobal("f1", function);
Object r2 = context.eval("f1()");
assertEquals(42, r2);
}
// Global function
{
Object result = context.eval("function a() { return 1; };a");
assertInstanceOf(QuickJSFunction.class, result);
QuickJSFunction function = (QuickJSFunction) result;
assertEquals(1, function.call());
assertEquals(1, function.call());
assertEquals(1, function.call());
assertEquals(1, function.call());
}
// Function with arguments
{
Object result = context.eval("function a(b) { return b + 1; };a");
assertInstanceOf(QuickJSFunction.class, result);
QuickJSFunction function = (QuickJSFunction) result;
assertEquals("a", function.getName());
assertEquals(42, function.call(41));
assertEquals(1, function.call(0));
assertEquals(2, function.call(1));
}
}
}
/**
* All supported java types can be set as global values in the QuickJS context
*
* @throws Exception
*/
@Test
public void testSetGlobal() throws Exception {
try (QuickJSRuntime runtime = new QuickJSRuntime();
QuickJSContext context = runtime.createContext()) {
{
context.setGlobal("a", 42);
Object result = context.eval("a");
assertEquals(42, result);
}
{
context.setGlobal("a", "hello");
Object result = context.eval("a");
assertEquals("hello", result);
}
{
context.setGlobal("a", true);
Object result = context.eval("a");
assertEquals(true, result);
}
{
context.setGlobal("a", 3.14);
Object result = context.eval("a");
assertEquals(3.14, result);
}
{
context.setGlobal("a", List.of(1, 2, 3));
Object result = context.eval("a[0]");
assertEquals(1, result);
}
{
context.setGlobal("a", Map.of("b", 42));
Object result = context.eval("a.b");
assertEquals(42, result);
}
{
context.setGlobal("f1", (String v) -> v + "!");
Object result = context.eval("f1('Hello World')");
assertEquals("Hello World!", result);
}
{
context.setGlobal("f2", (String v, String e) -> v + e);
Object result = context.eval("f2('Hello World', '!')");
assertEquals("Hello World!", result);
}
{
AtomicInteger ai = new AtomicInteger(0);
context.setGlobal("f3", (Integer v) -> ai.set(v));
context.eval("f3(42)");
assertEquals(42, ai.get());
}
{
AtomicInteger ai = new AtomicInteger(0);
context.setGlobal("f4", (Integer v, Integer x) -> ai.set(v + x));
context.eval("f4(40, 2)");
assertEquals(42, ai.get());
}
{
context.setGlobal("f5", () -> 42);
Object result = context.eval("f5()");
assertEquals(42, result);
}
{
// If the number of arguments could not be predefined use a VarArgFunction.
context.setGlobal("f6",
(VarArgFunction<Integer>) t -> Arrays.asList(t).stream()
.collect(Collectors.summingInt(x -> (Integer) x)));
Object result1 = context.eval("f6(1)");
assertEquals(1, result1);
Object result2 = context.eval("f6(1,2)");
assertEquals(3, result2);
Object result3 = context.eval("f6(1,2,3)");
assertEquals(6, result3);
Object result4 = context.eval("f6(1,2,3,4)");
assertEquals(10, result4);
}
{
// Packing the very same callback instance multiple times must not
// register a new host function every time.
final int before = context.hostFunctions.size();
Consumer<Integer> sameCallback = v -> {
};
context.setGlobal("cbA", sameCallback);
context.setGlobal("cbB", sameCallback);
assertEquals(before + 1, context.hostFunctions.size());
}
// Issue 12
{
context.setGlobal("setTimeout", (VarArgFunction<Object>) (in) -> {
try {
@SuppressWarnings("unchecked")
Function<List<Object>, Object> function = (Function<List<Object>, Object>) in[0];
long delay = ((Number) in[1]).longValue();
Thread.sleep(delay); // obviously terrible implementation, I'm just testing.
function.apply(List.of());
} catch (RuntimeException e) {
} catch (InterruptedException e) {
return e;
}
return null;
});
context.eval(" setTimeout(() => { true }, 1000)");
}
}
}
/**
* All supported java types can be retrieved from the global quickjs context
*
* @throws Exception
*/
@Test
public void testGetGlobal() throws Exception {
try (QuickJSRuntime runtime = new QuickJSRuntime();
QuickJSContext context = runtime.createContext()) {
{
context.setGlobal("a", 42);
Object result = context.getGlobal("a");
assertEquals(42, result);
}
{
context.setGlobal("a", "hello");
Object result = context.getGlobal("a");
assertEquals("hello", result);
}
{
context.setGlobal("a", true);
Object result = context.getGlobal("a");
assertEquals(true, result);
}
{
context.setGlobal("a", 3.14);
Object result = context.getGlobal("a");
assertEquals(3.14, result);
}
{
context.setGlobal("a", List.of(1, 2, 3));
Object result = context.getGlobal("a");
assertEquals(List.of(1, 2, 3), result);
}
{
context.setGlobal("a", Map.of("b", 42));
Object result = context.getGlobal("a");
assertEquals(Map.of("b", 42), result);
}
}
}
/**
* JS Object will be just wrapped as QuickJSObject. All modifications on the
* object will be visible on both the Java and the JS Side
*
* @throws Exception
*/
@Test
public void testNativeObjects() throws Exception {
try (QuickJSRuntime runtime = new QuickJSRuntime();
QuickJSContext context = runtime.createContext()) {
context.eval("var a = {a: 1, b: 'Hello'};");
Object result = context.getGlobal("a");
assertInstanceOf(QuickJSObject.class, result);
@SuppressWarnings("unchecked")
Map<String, Object> obj = (Map<String, Object>) result;
assertFalse(obj.isEmpty());
assertTrue(obj.containsValue(1));
assertTrue(obj.containsValue("Hello"));
assertTrue(obj.containsKey("a"));
assertTrue(obj.containsKey("b"));
assertEquals(2, obj.size());
assertEquals(1, obj.get("a"));
assertEquals("Hello", obj.get("b"));
Set<String> keys = obj.keySet();
assertEquals(2, keys.size());
assertTrue(keys.contains("a"));
assertTrue(keys.contains("b"));
assertNull(obj.get("c"));
Object r0 = context.eval("a.c");
assertNull(r0);
// One can add a value on Java side, and its visible on JS
obj.put("c", 42);
assertEquals(3, obj.size());
assertEquals(1, obj.get("a"));
assertEquals("Hello", obj.get("b"));
assertEquals(42, obj.get("c"));
Object r1 = context.eval("a.c");
assertEquals(42, r1);
// One can modify a value on java side and its visible on JS
obj.put("a", 10);
assertEquals(10, obj.get("a"));
Object r2 = context.eval("a.a");
assertEquals(10, r2);
// One can remove a value on java side and its visible on JS
obj.remove("b");
assertEquals(2, obj.size()); // a and c
assertEquals(10, obj.get("a"));
Object r3 = context.eval("a.b");
assertEquals(null, r3);
// One can clear native objects
context.eval("var b = {a: 1, b: 'Hello', c: 2};");
@SuppressWarnings("unchecked")
Map<String, Object> b = (Map<String, Object>) context.getGlobal("b");
assertEquals(3, b.size());
assertEquals(1, b.get("a"));
assertEquals("Hello", b.get("b"));
assertEquals(2, b.get("c"));
b.clear();
assertEquals(0, b.size());
assertTrue(b.isEmpty());
}
}
/**
* One can directly create native JS object on the java side using QuickJSObject
*
* @throws Exception
*/
@Test
public void testNativeObjectFromJavaSide() throws Exception {
try (QuickJSRuntime runtime = new QuickJSRuntime();
QuickJSContext context = runtime.createContext()) {
Map<String, Object> map = new QuickJSObject<>(context);
map.put("a", "Hello");
map.put("b", "World");
context.setGlobal("a", map);
assertEquals(2, map.keySet().size());
Object result = context.eval("a.a");
assertEquals("Hello", result);
result = context.eval("a.b");
assertEquals("World", result);
result = context.eval("a.c");
assertEquals(null, result);
// One can add a value on JS side, and its visible on Java
context.eval("a.c = 'test_value'");
assertEquals("test_value", map.get("c"));
// One can modify a value on JS side, and its visible on Java
context.eval("a.a = 'test_value'");
assertEquals("test_value", map.get("a"));
// One can remove a value on JS side, and its visible on Java
context.eval("delete a.b");
assertEquals(null, map.get("b"));
}
}
/**
* JS Arrays will be just wrapped as QuickJSArrays. All modifications on the
* array will be visible on both the Java and the JS side.
*/
@Test
public void testNativeArrays() throws Exception {
try (QuickJSRuntime runtime = new QuickJSRuntime();
QuickJSContext context = runtime.createContext()) {
context.eval("var a = [1, 2, 3];");
Object result = context.getGlobal("a");
assertInstanceOf(QuickJSArray.class, result);
@SuppressWarnings("unchecked")
List<Object> array = (List<Object>) result;
assertEquals(3, array.size());
assertEquals(1, array.get(0));
assertEquals(2, array.get(1));
assertEquals(3, array.get(2));
// One can add a value on Java side, and its visible on JS
array.add(4);
assertEquals(4, array.size());
assertEquals(1, array.get(0));
assertEquals(2, array.get(1));
assertEquals(3, array.get(2));
assertEquals(4, array.get(3));
Object r1 = context.eval("a[3]");
assertEquals(4, r1);
// Even add inbetween
array.add(1, 9);
assertEquals(5, array.size());
assertEquals(1, array.get(0));
assertEquals(9, array.get(1));
assertEquals(2, array.get(2));
// One can modify a value on java side and its visible on JS
array.set(0, 10);
assertEquals(10, array.get(0));
Object r2 = context.eval("a[0]");
assertEquals(10, r2);
// One can remove a value on java side and its visible on JS
array.remove(0);
assertEquals(4, array.size());
Object r3 = context.eval("a[0]");
assertEquals(9, r3);
// One can clear native arrays from the java side
assertFalse(array.isEmpty());
array.clear();
assertTrue(array.isEmpty());
}
}
/**
* One can create native JS arrays directly on the java side using QuickJSArrays
*
* @throws Exception
*/
@Test
public void testNativeArraysFromJavaSide() throws Exception {
try (QuickJSRuntime runtime = new QuickJSRuntime();
QuickJSContext context = runtime.createContext()) {
List<Object> list = new QuickJSArray<>(context);
list.add("a");
list.add("b");
assertEquals(2, list.size());
context.setGlobal("a", list);
assertEquals("a", context.eval("a[0]"));
assertEquals("b", context.eval("a[1]"));
// Modification on the js side are visible in the java object
// Add element
context.eval("a[2]='c';");
assertEquals(3, list.size());
assertEquals("c", list.get(2));
// Reassign element
context.eval("a[0]='d'");
assertEquals(3, list.size());
assertEquals("d", list.get(0));
// Delete elements
context.eval(" a.splice(2, 1); a.splice(1, 1);");
assertEquals(1, list.size());
assertEquals("d", list.get(0));
}
}
/**
* Several java functions can be put into the quickjs context and called as if
* they are native js functions
*
* @throws Exception
*/
@Test
public void exportJavaFunctionsToJS() throws Exception {
try (QuickJSRuntime runtime = new QuickJSRuntime();
QuickJSContext context = runtime.createContext()) {
BiFunction<Integer, Integer, Integer> add = (a, b) -> {
return a + b;
};
Function<Integer, Integer> square = (a) -> {
return a * a;
};
Supplier<Integer> random = () -> {
return 42;
};
AtomicInteger counter = new AtomicInteger();
Consumer<Integer> count = (a) -> {
counter.set(a);
};
AtomicInteger adder = new AtomicInteger();
BiConsumer<Integer, Integer> combine = (a, b) -> {
adder.set(a + b);
};
context.setGlobal("add", add);
context.setGlobal("square", square);
context.setGlobal("random", random);
context.setGlobal("count", count);
context.setGlobal("combine", combine);
Object result = context.eval("add(1, 2)");
assertEquals(3, result);
result = context.eval("square(2)");
assertEquals(4, result);
result = context.eval("random()");
assertEquals(42, result);
result = context.eval("count(1)");
assertEquals(1, counter.get());
result = context.eval("combine(3 , 4)");
assertEquals(7, adder.get());
// If one retrieves any javafunction from js it is returned as QuickJSFUnction
Object addBack = context.getGlobal("add");
assertInstanceOf(QuickJSFunction.class, addBack);
}
}
/**
* The runtime of the script can be limited in the Runtime object
*
* @throws Exception
*/
@Test
public void testScriptRuntimeLimit() throws Exception {
try (@SuppressWarnings("resource")
QuickJSRuntime runtime = new QuickJSRuntime().withScriptRuntimeLimit(1, TimeUnit.SECONDS);
QuickJSContext context = runtime.createContext()) {
try {
context.eval("while(true){}");
fail("Script runtime limit should have been reached");
} catch (Exception e) {
LOGGER.debug(e.getMessage());
}
}
}
/**
* The memory consumption of scripts can be limited by the runtime object to
* prevent faulty scripts to overload the host
*/
@Test
public void testScriptMemoryLimit() throws Exception {
try (@SuppressWarnings("resource")
QuickJSRuntime runtime = new QuickJSRuntime().withScriptMemoryLimit(10000);
QuickJSContext context = runtime.createContext()) {
try {
context.eval(
"const memoryHog = [];\nconst chunk = \"M_E_M_O_R_Y_\".repeat(100000);\nwhile (true) {memoryHog.push(chunk); }");
} catch (QuickJSException e) {
assertEquals("out of memory", e.getMessage());
}
}
}
/**
* JS exceptions thrown in the script are wrapped as QuickJSException
*
* @throws Exception
*/
@Test
public void testExceptionHandling() throws Exception {
try (QuickJSRuntime runtime = new QuickJSRuntime();
QuickJSContext context = runtime.createContext()) {
try {
context.eval("""
let a = 1;
let b = 0;
let c = a / b;
throw new Error('test');
""");
fail("Exception should have been thrown");
} catch (Exception e) {
assertInstanceOf(QuickJSException.class, e);
QuickJSException quickJSException = (QuickJSException) e;
assertEquals("test", quickJSException.getRawMessage());
assertEquals(" at <eval> (eval_script:4:11)\n",
quickJSException.getStack());
LOGGER.debug(e.getMessage());
}
}
}
/**
* Java exceptions thrown in java callbacks, are wrapped as js exceptions and
* then wrapped as QuickJSException. The message remains, the call stack is,
* however, replaced with the JS Callstack.
*
* @throws Exception
*/
@Test
public void testJavaExceptionHandling() throws Exception {
try (QuickJSRuntime runtime = new QuickJSRuntime();
QuickJSContext context = runtime.createContext()) {
BiFunction<Integer, Integer, Integer> add = (a, b) -> {
throw new RuntimeException("test");
};
context.setGlobal("add", add);
// This calls the java function add which throws an exception
context.eval("add(1, 2)");
fail("Exception should have been thrown");
} catch (Exception e) {
assertInstanceOf(QuickJSException.class, e);
QuickJSException quickJSException = (QuickJSException) e;
assertEquals("test", quickJSException.getRawMessage());
LOGGER.debug(e.getMessage());
}
}
/**
* Invoking a JS function directly from java is possible. Even nested calls to
* existing objects are supported
*
* @throws Exception
*/
@Test
public void testInvokeJSFunction() throws Exception {
try (QuickJSRuntime runtime = new QuickJSRuntime();
QuickJSContext context = runtime.createContext()) {
{
context.eval("function a(x, y) { return x + y; };");
Object result = context.invoke("a", 1, 2);
assertEquals(3, result);
}
{
context.eval("var g = {f: function(x, y) { return x + y; }};");
Object result = context.invoke("g.f", 1, 2);
assertEquals(3, result);
}
{
context.eval("var c = {b: {f: function(x, y) { return x + y; }}};");
Object result = context.invoke("c.b.f", 1, 2);
assertEquals(3, result);
}
}
}
public interface TestInterface {
int add(int a, int b);
int substract(int a, int b);
}
/**
* The global js context can be used as if it implements a java interface
*
* @throws Exception
*/
@Test
public void mapJSContextToJavaInterface() throws Exception {
try (QuickJSRuntime runtime = new QuickJSRuntime();
QuickJSContext context = runtime.createContext()) {
context.eval("function add(a, b) { return a + b; }; function substract(a, b) { return a - b; }; ");
TestInterface testInterface = context.getInterface(TestInterface.class);
assertEquals(3, testInterface.add(1, 2));
assertEquals(1, testInterface.substract(2, 1));
}
}
/**
* JS objects can be retrieved from the QuickJS context and mapped to java
* interfaces. This way the JS object can be used as if it implements a java
* interface.
*
* @throws Exception
*/
@Test
public void mapJSObjectToJavaInterface() throws Exception {
try (QuickJSRuntime runtime = new QuickJSRuntime();
QuickJSContext context = runtime.createContext()) {
@SuppressWarnings("unchecked")
QuickJSObject<String, Object> obj = (QuickJSObject<String, Object>) context.eval(
"let obj = {add: function(a, b) { return a + b; }, substract: function(a, b) { return a - b; }}; obj");
assertNotNull(obj);
TestInterface testInterface = context.getInterface(obj, TestInterface.class);
assertEquals(3, testInterface.add(1, 2));
assertEquals(1, testInterface.substract(2, 1));
}
}
/**
* High-level async support is provided. Promises from
* {@link QuickJSContext#evalAsync(String)} are wrapped by a
* CompletableFuture, which will be completed / completed exceptionally as soon
* as the underlying promise is completed / rejected
*
* @throws Exception
*/
@Test
public void promiseSupport() throws Exception {
try (QuickJSRuntime runtime = new QuickJSRuntime();
QuickJSContext context = runtime.createContext()) {
CompletableFuture<Object> r1 = context.evalAsync("let trigger;\n" + //
"const manualPromise = new Promise((resolve, reject) => {\n" + //
" // Assign the internal resolve function to our outside variable\n" + //
" trigger = resolve; \n" + //
"});\n" + //
"manualPromise\n");
assertFalse(r1.isDone());
CompletableFuture<Object> r2 = context.evalAsync("await trigger(\"Classic resolve\");");
// Context.poll is required to trigger further steps in the async runtime
while (context.poll()) {
Thread.sleep(10);
}
assertTrue(r1.isDone());
assertTrue(r2.isDone());
}
}
/**
* High-level async support is provided. Promises from
* {@link QuickJSContext#evalAsync(String)} are wrapped by a
* CompletableFuture, which will be completed as soon
* as the underlying promise is completed
*
* @throws Exception
*/
@Test
public void simplePromiseSupport() throws Exception {
try (QuickJSRuntime runtime = new QuickJSRuntime();
QuickJSContext context = runtime.createContext()) {
CompletableFuture<Object> r1 = context.evalAsync("await \"Classic resolve\" ");
assertNotNull(r1);
assertFalse(r1.isDone());
while (context.poll()) {
Thread.sleep(10);
}
assertTrue(r1.isDone());
assertEquals("Classic resolve", r1.join());
}
}
/**
* High-level async support is provided. Promises from
* {@link QuickJSContext#evalAsync(String)} are wrapped by a
* CompletableFuture, which will be completed exceptionally as soon
* as the underlying promise is rejected
*
* @throws Exception
*/
@Test
public void simplePromiseErrSupport() throws Exception {
try (QuickJSRuntime runtime = new QuickJSRuntime();
QuickJSContext context = runtime.createContext()) {
CompletableFuture<Object> r1 = context.evalAsync("throw Err('hello') ");
assertNotNull(r1);
assertFalse(r1.isDone());
while (context.poll()) {
Thread.sleep(10);
}
assertTrue(r1.isCompletedExceptionally());
}
}
/**
* Completable futures are internally wrapped with promises and can be treated
* like promises
*/
@SuppressWarnings("rawtypes")
@Test
public void completableFutureSupport() throws Exception {
try (QuickJSRuntime runtime = new QuickJSRuntime();
QuickJSContext context = runtime.createContext()) {
{
CompletableFuture<Object> promise = new CompletableFuture<>();
context.setGlobal("p0", promise);
CompletableFuture<Object> r1 = context.evalAsync("await p0");
while (context.poll()) {
Thread.sleep(10);
}
promise.complete(53);
while (context.poll()) {
Thread.sleep(10);
}
assertEquals(53, promise.join());
assertEquals(53, r1.join());
}
{
CompletableFuture<Object> promise = new CompletableFuture<>();
//
context.setGlobal("p", promise);
CompletableFuture result = context.evalAsync("await p.then((v) => { return v * 3; });");
LOGGER.debug(result);
while (context.poll()) {
Thread.sleep(10);
}
assertFalse(((CompletableFuture) result).isDone());
promise.complete(54);
while (context.poll()) {
Thread.sleep(10);
}
assertTrue(((CompletableFuture) result).isDone());
assertEquals(162, ((CompletableFuture) result).join());
}
}
}
/**
* On can return completable futures from java functions and these are treated
* like promises on the js side
*/
@SuppressWarnings("rawtypes")
@Test
public void functionsCanReturnCompletableFutures() throws Exception {
try (QuickJSRuntime runtime = new QuickJSRuntime();
QuickJSContext context = runtime.createContext()) {
CompletableFuture<Integer> cf = new CompletableFuture<>();
Supplier<CompletableFuture<Integer>> answer = () -> {
return cf;
};
context.setGlobal("answer", answer);
CompletableFuture<?> result = context.evalAsync("await answer()");
// Result is not completed here
assertFalse(((CompletableFuture) result).isDone());
while (context.poll()) {
Thread.sleep(10);
}
// Even after emptying the event pipeline it is still not completed
assertFalse(((CompletableFuture) result).isDone());
// Now finally complete it
cf.complete(42);
// Empty the event pipeline -> the CompletableFuture will be completed here
while (context.poll()) {
Thread.sleep(10);
}
assertTrue(((CompletableFuture) result).isDone());
assertEquals(42, ((CompletableFuture) result).join());
}
}
/**
* Test constructors
*/
@Test
public void testConstructors() throws Exception {
try (QuickJSRuntime runtime = new QuickJSRuntime();
QuickJSContext context = runtime.createContext()) {
String s = "class Foo { constructor(x) { this.a = x; } }";
context.eval(s);
Object o = context.construct("Foo", 1);
assertTrue(o instanceof QuickJSObject);
QuickJSObject object = (QuickJSObject) o;
o = object.get("a");
assertEquals(1, o);
}
}
}