Debian Codegraph @

rhino/testsrc/org/mozilla/javascript/drivers/ScriptTestsBase.java

raw symbols SCIP
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 package org.mozilla.javascript.drivers;
6
7 import org.junit.Test;
8 import org.junit.runner.RunWith;
9 import org.junit.runners.BlockJUnit4ClassRunner;
10 import org.mozilla.javascript.Context;
11 import org.mozilla.javascript.JavaScriptException;
12 import org.mozilla.javascript.Scriptable;
13 import org.mozilla.javascript.tools.shell.Global;
14
15 import java.io.*;
16
17 import static org.junit.Assert.*;
18
19 /**
20 * This class is used for creating test scripts that are loaded from JS scripts. Each test must
21 * be represented by a class that extends this class, and has a "RhinoTest" annotation at the
22 * class level that returns the file name of the script to execute.
23 */
24
25 @RunWith(BlockJUnit4ClassRunner.class)
26 public abstract class ScriptTestsBase {
27
28 private Object executeRhinoScript(int optLevel) {
29 RhinoTest anno = this.getClass().getAnnotation(RhinoTest.class);
30 assertNotNull(anno);
31
32 int jsVersion = Context.VERSION_1_8;
33 LanguageVersion jsVersionAnnotation = this.getClass().getAnnotation(LanguageVersion.class);
34 if (jsVersionAnnotation != null) {
35 jsVersion = jsVersionAnnotation.value();
36 Context.checkLanguageVersion(jsVersion);
37 }
38
39 Reader script = null;
40 String suiteName = null;
41
42 Context cx = Context.enter();
43 try {
44 if (!"".equals(anno.value())) {
45 script = new InputStreamReader(new FileInputStream(anno.value()), "UTF-8");
46 suiteName = anno.value();
47 } else if (!"".equals(anno.inline())) {
48 script = new StringReader("load('testsrc/assert.js');\n" + anno.inline() + "\n" + "'success';");
49 suiteName = "inline.js";
50 }
51
52 cx.setOptimizationLevel(optLevel);
53 cx.setLanguageVersion(jsVersion);
54
55 Global global = new Global(cx);
56
57 Scriptable scope = cx.newObject(global);
58 scope.setPrototype(global);
59 scope.setParentScope(null);
60
61 return cx.evaluateReader(scope, script, suiteName, 1, null);
62 } catch (JavaScriptException ex) {
63 fail(String.format("%s%n%s", ex.getMessage(), ex.getScriptStackTrace()));
64 return null;
65 } catch (Exception e) {
66 throw new RuntimeException(e);
67 } finally {
68 Context.exit();
69 try {
70 if (null != script) script.close();
71 } catch (IOException e) {
72 }
73 }
74 }
75
76 @Test
77 public void rhinoTestNoOpt() {
78 assertEquals("success", executeRhinoScript(-1));
79 }
80
81 @Test
82 public void rhinoTestOpt0() {
83 assertEquals("success", executeRhinoScript(0));
84 }
85
86 @Test
87 public void rhinoTestOpt9() {
88 assertEquals("success", executeRhinoScript(9));
89 }
90 }