| 1 |
|
| 2 |
|
| 3 |
|
| 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 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
public class WriteReadOnlyPropertyTest { |
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
@Test |
| 30 |
public void testWriteReadOnly_accepted() throws Exception { |
| 31 |
testWriteReadOnly(true); |
| 32 |
} |
| 33 |
|
| 34 |
|
| 35 |
|
| 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 |
|
| 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 |
|