Debian Codegraph @

rhino/testsrc/org/mozilla/javascript/tests/WriteReadOnlyPropertyTest.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 java.lang.reflect.Method;
8
9 import org.junit.Assert;
10 import org.junit.Test;
11 import org.mozilla.javascript.Context;
12 import org.mozilla.javascript.ContextAction;
13 import org.mozilla.javascript.ContextFactory;
14 import org.mozilla.javascript.EcmaError;
15 import org.mozilla.javascript.ScriptableObject;
16
17 /**
18 * Test that read-only properties can be... set when needed.
19 * This was the standard behavior in Rhino until 1.7R2 but has changed then.
20 * It is needed by HtmlUnit to simulate IE as well as FF2 (but not FF3).
21 * @see <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=519933">Rhino bug 519933</a>
22 * @author Marc Guillemot
23 */
24 public class WriteReadOnlyPropertyTest {
25
26 /**
27 * @throws Exception if the test fails
28 */
29 @Test
30 public void testWriteReadOnly_accepted() throws Exception {
31 testWriteReadOnly(true);
32 }
33
34 /**
35 * @throws Exception if the test fails
36 */
37 @Test
38 public void testWriteReadOnly_throws() throws Exception {
39 try {
40 testWriteReadOnly(false);
41 Assert.fail();
42 }
43 catch (EcmaError e) {
44 Assert.assertTrue(e.getMessage(), e.getMessage().contains("Cannot set property myProp that has only a getter"));
45 }
46 }
47
48 void testWriteReadOnly(final boolean acceptWriteReadOnly) throws Exception {
49 final Method readMethod = Foo.class.getMethod("getMyProp", (Class[])null);
50 final Foo foo = new Foo("hello");
51 foo.defineProperty("myProp", null, readMethod, null, ScriptableObject.EMPTY);
52
53 final String script = "foo.myProp = 123; foo.myProp";
54
55 final ContextAction action = new ContextAction() {
56 public Object run(final Context cx) {
57
58 final ScriptableObject top = cx.initStandardObjects();
59 ScriptableObject.putProperty(top, "foo", foo);
60
61 cx.evaluateString(top, script, "script", 0, null);
62 return null;
63 }
64 };
65
66 final ContextFactory contextFactory = new ContextFactory() {
67 @Override
68 protected boolean hasFeature(final Context cx, final int featureIndex) {
69 if (Context.FEATURE_STRICT_MODE == featureIndex) {
70 return !acceptWriteReadOnly;
71 }
72 return super.hasFeature(cx, featureIndex);
73 }
74 };
75 contextFactory.call(action);
76 }
77
78 /**
79 * Simple utility allowing to better see the concerned scope while debugging
80 */
81 static class Foo extends ScriptableObject
82 {
83 final String prop_;
84 Foo(final String label)
85 {
86 prop_ = label;
87 }
88
89 @Override
90 public String getClassName()
91 {
92 return "Foo";
93 }
94
95 public String getMyProp()
96 {
97 return prop_;
98 }
99 }
100 }
101