changeset 16177:e6464f96bdb2

8006412: Improve toString method of ScriptObjectMirror class Reviewed-by: jlaskey, lagergren
author sundar
date Wed, 16 Jan 2013 17:58:51 +0530
parents 8678c9abbb99
children 2704dd3b2691
files nashorn/src/jdk/nashorn/api/scripting/ScriptObjectMirror.java nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineTest.java
diffstat 2 files changed, 33 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/nashorn/src/jdk/nashorn/api/scripting/ScriptObjectMirror.java	Wed Jan 16 07:06:40 2013 -0400
+++ b/nashorn/src/jdk/nashorn/api/scripting/ScriptObjectMirror.java	Wed Jan 16 17:58:51 2013 +0530
@@ -38,6 +38,7 @@
 import jdk.nashorn.internal.runtime.Context;
 import jdk.nashorn.internal.runtime.ScriptFunction;
 import jdk.nashorn.internal.runtime.ScriptObject;
+import jdk.nashorn.internal.runtime.ScriptRuntime;
 import netscape.javascript.JSObject;
 
 /**
@@ -67,6 +68,16 @@
         return sobj.hashCode();
     }
 
+    @Override
+    public String toString() {
+        return inGlobal(new Callable<String>() {
+            @Override
+            public String call() {
+                return ScriptRuntime.safeToString(sobj);
+            }
+        });
+    }
+
     private <V> V inGlobal(final Callable<V> callable) {
         final ScriptObject oldGlobal = Context.getGlobal();
         final boolean globalChanged = (oldGlobal != global);
--- a/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineTest.java	Wed Jan 16 07:06:40 2013 -0400
+++ b/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineTest.java	Wed Jan 16 17:58:51 2013 +0530
@@ -46,6 +46,7 @@
 import javax.script.ScriptException;
 import jdk.nashorn.internal.runtime.Version;
 import netscape.javascript.JSObject;
+import org.testng.Assert;
 import org.testng.TestNG;
 import org.testng.annotations.Test;
 
@@ -859,4 +860,25 @@
             fail(t.getMessage());
         }
     }
+
+    @Test
+    public void scriptObjectMirrorToStringTest() {
+        final ScriptEngineManager m = new ScriptEngineManager();
+        final ScriptEngine e = m.getEngineByName("nashorn");
+        try {
+            Object obj = e.eval("new TypeError('wrong type')");
+            Assert.assertEquals(obj.toString(), "TypeError: wrong type", "toString returns wrong value");
+        } catch (final Throwable t) {
+            t.printStackTrace();
+            fail(t.getMessage());
+        }
+
+        try {
+            Object obj = e.eval("function func() { print('hello'); }");
+            Assert.assertEquals(obj.toString(), "function func() { print('hello'); }", "toString returns wrong value");
+        } catch (final Throwable t) {
+            t.printStackTrace();
+            fail(t.getMessage());
+        }
+    }
 }