View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *   http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.jexl3.scripting;
19  
20  import java.io.StringWriter;
21  import javax.script.Compilable;
22  import javax.script.CompiledScript;
23  
24  import javax.script.ScriptEngine;
25  import javax.script.ScriptEngineManager;
26  import org.junit.Assert;
27  import org.junit.Test;
28  
29  public class JexlScriptEngineOptionalTest {
30      private final JexlScriptEngineFactory factory = new JexlScriptEngineFactory();
31      private final ScriptEngineManager manager = new ScriptEngineManager();
32      private final ScriptEngine engine = manager.getEngineByName("jexl");
33  
34      @Test
35      public void testOutput() throws Exception {
36          final String output = factory.getOutputStatement("foo\u00a9bar");
37          Assert.assertEquals("JEXL.out.print('foo\\u00a9bar')", output);
38          // redirect output to capture evaluation result
39          final StringWriter outContent = new StringWriter();
40          engine.getContext().setWriter(outContent);
41          engine.eval(output);
42          Assert.assertEquals("foo\u00a9bar", outContent.toString());
43      }
44  
45      @Test
46      public void testError() throws Exception {
47          final String error = "JEXL.err.print('ERROR')";
48          // redirect error to capture evaluation result
49          final StringWriter outContent = new StringWriter();
50          engine.getContext().setErrorWriter(outContent);
51          engine.eval(error);
52          Assert.assertEquals("ERROR", outContent.toString());
53      }
54  
55      @Test
56      public void testCompilable() throws Exception {
57          Assert.assertTrue("Engine should implement Compilable", engine instanceof Compilable);
58          final Compilable cengine = (Compilable) engine;
59          final CompiledScript script = cengine.compile("40 + 2");
60          Assert.assertEquals(42, script.eval());
61          Assert.assertEquals(42, script.eval());
62      }
63  }