| 1 |
package org.mozilla.javascript.tests; |
| 2 |
|
| 3 |
import java.io.FileReader; |
| 4 |
import java.io.IOException; |
| 5 |
import org.junit.Test; |
| 6 |
import org.mozilla.javascript.Context; |
| 7 |
import org.mozilla.javascript.NativeArray; |
| 8 |
import org.mozilla.javascript.RhinoException; |
| 9 |
import org.mozilla.javascript.Scriptable; |
| 10 |
import org.mozilla.javascript.ScriptableObject; |
| 11 |
import org.mozilla.javascript.Undefined; |
| 12 |
import org.mozilla.javascript.tools.shell.Global; |
| 13 |
|
| 14 |
import static org.junit.Assert.*; |
| 15 |
|
| 16 |
public class ComparatorTest { |
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
private void idChk(Object o1, Object o2, int expected) { |
| 24 |
assertEquals(expected, new ScriptableObject.KeyComparator().compare(o1, o2)); |
| 25 |
assertEquals(-expected, new ScriptableObject.KeyComparator().compare(o2, o1)); |
| 26 |
} |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
@Test |
| 34 |
public void testObjectIDComparator() { |
| 35 |
idChk(0, 0, 0); |
| 36 |
idChk(1, 0, 1); |
| 37 |
idChk(0, 1, -1); |
| 38 |
idChk("a", "a", 0); |
| 39 |
idChk("b", "a", 0); |
| 40 |
idChk("a", "b", 0); |
| 41 |
idChk("a", 1, 1); |
| 42 |
idChk(1, "a", -1); |
| 43 |
} |
| 44 |
|
| 45 |
private void aChk(Object o1, Object o2, int expected) { |
| 46 |
assertEquals(expected, new NativeArray.ElementComparator().compare(o1, o2)); |
| 47 |
assertEquals(-expected, new NativeArray.ElementComparator().compare(o2, o1)); |
| 48 |
} |
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
@Test |
| 56 |
public void testArrayComparator() { |
| 57 |
aChk("a", "b", -1); |
| 58 |
aChk("b", "a", 1); |
| 59 |
aChk("a", "a", 0); |
| 60 |
aChk(Scriptable.NOT_FOUND, "a", 1); |
| 61 |
aChk("a", Scriptable.NOT_FOUND, -1); |
| 62 |
aChk(Scriptable.NOT_FOUND, Scriptable.NOT_FOUND, 0); |
| 63 |
aChk(Undefined.instance, "a", 1); |
| 64 |
aChk("a", Undefined.instance, -1); |
| 65 |
aChk(Undefined.instance, Undefined.instance, 0); |
| 66 |
aChk(Undefined.instance, Scriptable.NOT_FOUND, -1); |
| 67 |
aChk(Scriptable.NOT_FOUND, Undefined.instance, 1); |
| 68 |
} |
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
@Test |
| 75 |
public void testCustomComparator() |
| 76 |
throws IOException |
| 77 |
{ |
| 78 |
Context cx = Context.enter(); |
| 79 |
Global global = new Global(cx); |
| 80 |
Scriptable root = cx.newObject(global); |
| 81 |
FileReader fr = new FileReader("testsrc/jstests/extensions/custom-comparators.js"); |
| 82 |
|
| 83 |
try { |
| 84 |
cx.evaluateReader(root, fr, "custom-comparators.js", 1, null); |
| 85 |
} catch (RhinoException re) { |
| 86 |
System.err.println(re.getScriptStackTrace()); |
| 87 |
throw re; |
| 88 |
} finally { |
| 89 |
Context.exit(); |
| 90 |
} |
| 91 |
} |
| 92 |
} |