8012792: print function defined in engine.js does not handle multiple arguments
authorsundar
Mon, 29 Jul 2013 18:07:20 +0530
changeset 19107 721939a7971c
parent 19105 a01ba9d17eab
child 19108 41b35dc6bab7
child 19236 73d242d205f9
8012792: print function defined in engine.js does not handle multiple arguments Reviewed-by: hannesw
nashorn/src/jdk/nashorn/api/scripting/resources/engine.js
nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineTest.java
--- a/nashorn/src/jdk/nashorn/api/scripting/resources/engine.js	Fri Jul 26 20:10:47 2013 +0530
+++ b/nashorn/src/jdk/nashorn/api/scripting/resources/engine.js	Mon Jul 29 18:07:20 2013 +0530
@@ -39,12 +39,20 @@
     }
 });
 
-function print(str) {
+function print() {
     var writer = context.getWriter();
     if (! (writer instanceof java.io.PrintWriter)) {
         writer = new java.io.PrintWriter(writer);
     }
-    writer.println(String(str));
+    
+    var buf = new java.lang.StringBuilder();
+    for (var i = 0; i < arguments.length; i++) {
+        if (i != 0) {
+            buf.append(' ');
+        }
+        buf.append(String(arguments[i]));
+    }
+    writer.println(buf.toString());
 }
 
 /**
--- a/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineTest.java	Fri Jul 26 20:10:47 2013 +0530
+++ b/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineTest.java	Mon Jul 29 18:07:20 2013 +0530
@@ -1220,4 +1220,38 @@
         Assert.assertEquals(itf.test1(42, "a", "b"), "i == 42, strings instanceof java.lang.String[] == true, strings == [a, b]");
         Assert.assertEquals(itf.test2(44, "c", "d", "e"), "arguments[0] == 44, arguments[1] instanceof java.lang.String[] == true, arguments[1] == [c, d, e]");
     }
+
+    @Test
+    // check that print function prints arg followed by newline char
+    public void printTest() {
+        final ScriptEngineManager m = new ScriptEngineManager();
+        final ScriptEngine e = m.getEngineByName("nashorn");
+        final StringWriter sw = new StringWriter();
+        e.getContext().setWriter(sw);
+        try {
+            e.eval("print('hello')");
+        } catch (final Throwable t) {
+            t.printStackTrace();
+            fail(t.getMessage());
+        }
+
+        assertEquals(sw.toString(), "hello\n");
+    }
+
+    @Test
+    // check that print prints all arguments (more than one)
+    public void printManyTest() {
+        final ScriptEngineManager m = new ScriptEngineManager();
+        final ScriptEngine e = m.getEngineByName("nashorn");
+        final StringWriter sw = new StringWriter();
+        e.getContext().setWriter(sw);
+        try {
+            e.eval("print(34, true, 'hello')");
+        } catch (final Throwable t) {
+            t.printStackTrace();
+            fail(t.getMessage());
+        }
+
+        assertEquals(sw.toString(), "34 true hello\n");
+    }
 }