11package com .baeldung .chicory ;
22
33import com .dylibso .chicory .runtime .ExportFunction ;
4+ import com .dylibso .chicory .runtime .HostFunction ;
45import com .dylibso .chicory .runtime .Instance ;
6+ import com .dylibso .chicory .runtime .Store ;
57import com .dylibso .chicory .wasm .Parser ;
8+ import com .dylibso .chicory .wasm .WasmModule ;
9+ import com .dylibso .chicory .wasm .types .FunctionType ;
10+ import com .dylibso .chicory .wasm .types .ValType ;
611import org .junit .jupiter .api .Test ;
712
813import java .io .InputStream ;
14+ import java .util .List ;
915
1016import static org .junit .jupiter .api .Assertions .assertEquals ;
1117import static org .junit .jupiter .api .Assertions .assertNotNull ;
18+ import static org .junit .jupiter .api .Assertions .assertThrows ;
1219
1320class ChicoryUnitTest {
1421
1522 @ Test
1623 void givenAddModule_whenCallingAddWithTwoAndForty_thenResultIsFortyTwo () {
17- InputStream wasm = getClass ().getResourceAsStream ("/wasm /add.wasm" );
24+ InputStream wasm = getClass ().getResourceAsStream ("/chicory /add.wasm" );
1825 assertNotNull (wasm );
1926
20- var module = Parser .parse (wasm );
27+ WasmModule module = Parser .parse (wasm );
2128 Instance instance = Instance .builder (module ).build ();
2229 ExportFunction add = instance .export ("add" );
2330
2431 long [] result = add .apply (2 , 40 );
2532
2633 assertEquals (42 , (int ) result [0 ]);
2734 }
28- }
35+
36+ @ Test
37+ void givenImportDouble_whenCallingUseDouble_thenResultIsDoubled () {
38+ InputStream wasm = getClass ().getResourceAsStream ("/chicory/imports.wasm" );
39+ assertNotNull (wasm );
40+
41+ HostFunction doubleFn = new HostFunction (
42+ "host" ,
43+ "double" ,
44+ FunctionType .of (List .of (ValType .I32 ), List .of (ValType .I32 )),
45+ (Instance instance , long ... args ) -> new long [] { args [0 ] * 2 }
46+ );
47+
48+ Store store = new Store ();
49+ store .addFunction (doubleFn );
50+
51+ WasmModule module = Parser .parse (wasm );
52+ Instance instance = store .instantiate ("imports" , module );
53+ ExportFunction useDouble = instance .export ("useDouble" );
54+
55+ long [] result = useDouble .apply (21 );
56+
57+ assertEquals (42L , result [0 ]);
58+ }
59+
60+ @ Test
61+ void whenInstantiatingModuleWithoutRequiredImport_thenErrorIsThrown () {
62+ InputStream wasm = getClass ().getResourceAsStream ("/chicory/imports.wasm" );
63+ assertNotNull (wasm );
64+
65+ WasmModule module = Parser .parse (wasm );
66+
67+ assertThrows (RuntimeException .class , () -> {
68+ Instance .builder (module ).build ();
69+ });
70+ }
71+
72+ @ Test
73+ void whenRequestingMissingExport_thenErrorIsThrown () {
74+ InputStream wasm = getClass ().getResourceAsStream ("/chicory/add.wasm" );
75+ assertNotNull (wasm );
76+
77+ WasmModule module = Parser .parse (wasm );
78+ Instance instance = Instance .builder (module ).build ();
79+
80+ assertThrows (RuntimeException .class , () -> instance .export ("sum" ));
81+ }
82+
83+ }
0 commit comments