Debian Codegraph @

rhino/testsrc/org/mozilla/javascript/tests/GeneratedMethodNameTest.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.tests;
6
7 import org.mozilla.javascript.Context;
8 import org.mozilla.javascript.ContextFactory;
9 import org.mozilla.javascript.Script;
10 import org.mozilla.javascript.Scriptable;
11
12 import junit.framework.TestCase;
13
14 /**
15 * Takes care that the name of the method generated for a function "looks like" the original function name.
16 * See https://bugzilla.mozilla.org/show_bug.cgi?id=460726
17 * @author Marc Guillemot
18 */
19 public class GeneratedMethodNameTest extends TestCase
20 {
21 public void testStandardFunction() throws Exception {
22 final String scriptCode = "function myFunc() {\n"
23 + " var m = javaNameGetter.readCurrentFunctionJavaName();\n"
24 + " if (m != 'myFunc') throw 'got ' + m;"
25 + "}\n"
26 + "myFunc();";
27 doTest(scriptCode);
28 }
29
30 public void testFunctionDollar() throws Exception {
31 final String scriptCode = "function $() {\n"
32 + " var m = javaNameGetter.readCurrentFunctionJavaName();\n"
33 + " if (m != '$') throw 'got ' + m;"
34 + "}\n"
35 + "$();";
36 doTest(scriptCode);
37 }
38
39 public void testScriptName() throws Exception {
40 final String scriptCode =
41 "var m = javaNameGetter.readCurrentFunctionJavaName();\n"
42 + "if (m != 'script') throw 'got ' + m;";
43 doTest(scriptCode);
44 }
45
46 public void testConstructor() throws Exception {
47 final String scriptCode = "function myFunc() {\n"
48 + " var m = javaNameGetter.readCurrentFunctionJavaName();\n"
49 + " if (m != 'myFunc') throw 'got ' + m;"
50 + "}\n"
51 + "new myFunc();";
52 doTest(scriptCode);
53 }
54
55 public void testAnonymousFunction() throws Exception {
56 final String scriptCode = "var myFunc = function() {\n"
57 + " var m = javaNameGetter.readCurrentFunctionJavaName();\n"
58 + " if (m != 'anonymous') throw 'got ' + m;"
59 + "}\n"
60 + "myFunc();";
61 doTest(scriptCode);
62 }
63
64 public class JavaNameGetter {
65 public String readCurrentFunctionJavaName() {
66 final Throwable t = new RuntimeException();
67 // remove prefix and suffix of method name
68 return t.getStackTrace()[8].getMethodName().
69 replaceFirst("_[^_]*_(.*)_[^_]*", "$1");
70 }
71 }
72
73 public void doTest(final String scriptCode) throws Exception {
74 final Context cx = ContextFactory.getGlobal().enterContext();
75 try {
76 Scriptable topScope = cx.initStandardObjects();
77 topScope.put("javaNameGetter", topScope, new JavaNameGetter());
78 Script script = cx.compileString(scriptCode, "myScript", 1, null);
79 script.exec(cx, topScope);
80 } finally {
81 Context.exit();
82 }
83 }
84 }