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 static org.junit.jupiter.api.Assertions.assertEquals;
21  import static org.junit.jupiter.api.Assertions.assertTrue;
22  
23  import java.io.StringWriter;
24  
25  import javax.script.Compilable;
26  import javax.script.CompiledScript;
27  import javax.script.ScriptEngine;
28  import javax.script.ScriptEngineManager;
29  
30  import org.junit.jupiter.api.Test;
31  
32  public class JexlScriptEngineOptionalTest {
33      private final JexlScriptEngineFactory factory = new JexlScriptEngineFactory();
34      private final ScriptEngineManager manager = new ScriptEngineManager();
35      private final ScriptEngine engine = manager.getEngineByName("jexl");
36  
37      @Test
38      public void testCompilable() throws Exception {
39          assertTrue(engine instanceof Compilable, "Engine should implement Compilable");
40          final Compilable cengine = (Compilable) engine;
41          final CompiledScript script = cengine.compile("40 + 2");
42          assertEquals(42, script.eval());
43          assertEquals(42, script.eval());
44      }
45  
46      @Test
47      public void testError() throws Exception {
48          final String error = "JEXL.err.print('ERROR')";
49          // redirect error to capture evaluation result
50          final StringWriter outContent = new StringWriter();
51          engine.getContext().setErrorWriter(outContent);
52          engine.eval(error);
53          assertEquals("ERROR", outContent.toString());
54      }
55  
56      @Test
57      public void testOutput() throws Exception {
58          final String output = factory.getOutputStatement("foo\u00a9bar");
59          assertEquals("JEXL.out.print('foo\\u00a9bar')", output);
60          // redirect output to capture evaluation result
61          final StringWriter outContent = new StringWriter();
62          engine.getContext().setWriter(outContent);
63          engine.eval(output);
64          assertEquals("foo\u00a9bar", outContent.toString());
65      }
66  }