Skip to content

Commit 64777a3

Browse files
committed
Testing that JSON.stringify() invokes toJSON() of foreign objects.
1 parent ee1eb02 commit 64777a3

File tree

1 file changed

+32
-4
lines changed

1 file changed

+32
-4
lines changed

graal-js/src/com.oracle.truffle.js.test/src/com/oracle/truffle/js/test/interop/JSONStringifyInteropTest.java

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,8 @@
5151
import org.graalvm.polyglot.Context;
5252
import org.graalvm.polyglot.HostAccess;
5353
import org.graalvm.polyglot.Value;
54+
import org.graalvm.polyglot.proxy.ProxyExecutable;
55+
import org.graalvm.polyglot.proxy.ProxyObject;
5456
import org.junit.Test;
5557

5658
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
@@ -85,12 +87,38 @@ public void testForeignExecutable() {
8587
}
8688
}
8789

90+
private static void checkStringification(Object objectToStringify, String expectedResult) {
91+
try (Context context = JSTest.newContextBuilder().allowHostAccess(HostAccess.ALL).build()) {
92+
context.getBindings(ID).putMember("objectToStringify", objectToStringify);
93+
Value result = context.eval(ID, "JSON.stringify(objectToStringify)");
94+
assertEquals(expectedResult, result.asString());
95+
}
96+
}
97+
8898
@Test
8999
public void testNonReadableMembers() {
90-
try (Context context = JSTest.newContextBuilder().allowHostAccess(HostAccess.ALL).build()) {
91-
context.getBindings(ID).putMember("myObj", new InvocableMemberObject(Collections.singletonMap("someKey", "someValue")));
92-
Value result = context.eval(ID, "JSON.stringify(myObj)");
93-
assertEquals("{}", result.asString());
100+
checkStringification(new InvocableMemberObject(Collections.singletonMap("someKey", "someValue")), "{}");
101+
}
102+
103+
@Test
104+
public void testToJSONOfProxyObject() {
105+
Object object = ProxyObject.fromMap(Collections.singletonMap("toJSON", new ProxyExecutable() {
106+
@Override
107+
public Object execute(Value... arguments) {
108+
return "fromToJSON";
109+
}
110+
}));
111+
checkStringification(object, "\"fromToJSON\"");
112+
}
113+
114+
@Test
115+
public void testToJSONOfHostObject() {
116+
checkStringification(new HostObjectWithToJSON(), "\"HostObjectWithToJSON\"");
117+
}
118+
119+
public static class HostObjectWithToJSON {
120+
public Object toJSON(@SuppressWarnings("unused") String key) {
121+
return "HostObjectWithToJSON";
94122
}
95123
}
96124

0 commit comments

Comments
 (0)