Skip to content

Commit

Permalink
Add registerMapAdapter test
Browse files Browse the repository at this point in the history
  • Loading branch information
seven332 committed Nov 6, 2021
1 parent 4d4e173 commit 20a0038
Showing 1 changed file with 54 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,13 @@
import org.junit.Test;

import java.lang.reflect.Type;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import static org.junit.Assert.assertEquals;

import android.util.ArrayMap;

public class TypeAdapterTest {

@Test
Expand Down Expand Up @@ -68,4 +71,55 @@ public TypeAdapter<?> create(QuickJS quickJS, Type type) {
return null;
}
}

@Test
public void registerMapAdapter() {
Type mapType = new JavaType<Map<String, String>>() {}.type;

QuickJS quickJS = new QuickJS.Builder()
.registerTypeAdapter(mapType, new MapTypeAdapter().nullable())
.build();
try (JSRuntime runtime = quickJS.createJSRuntime()) {
try (JSContext context = runtime.createJSContext()) {
Map<String, String> actual = context.evaluate(
"a = { key1: \"value1\", key2: \"value2\" }", "test.js", mapType);
Map<String, String> expected = new ArrayMap<>();
expected.put("key1", "value1");
expected.put("key2", "value2");
assertEquals(expected, actual);
}
}
}

private static class MapTypeAdapter extends TypeAdapter<Map<String, String>> {
@Override
public JSValue toJSValue(JSContext context, Map<String, String> value) {
JSObject jo = context.createJSObject();
value.forEach((k, v) -> {
if (k == null) return;
jo.setProperty(k, context.createJSString(v));
});
return jo;
}

@Override
public Map<String, String> fromJSValue(JSContext context, JSValue value) {
JSObject jo = value.cast(JSObject.class);
JSFunction keysFunction = context.getGlobalObject()
.getProperty("Object").cast(JSObject.class)
.getProperty("keys").cast(JSFunction.class);

TypeAdapter<String[]> adapter = context.quickJS.getAdapter(String[].class);
JSValue keysResult = keysFunction.invoke(null, new JSValue[] { jo });
String[] keys = adapter.fromJSValue(context, keysResult);

Map<String, String> map = new ArrayMap<>(keys.length);
for (String key: keys) {
String val = jo.getProperty(key).cast(JSString.class).getString();
map.put(key, val);
}

return map;
}
}
}

0 comments on commit 20a0038

Please sign in to comment.