Add unit tests used in vm1

This commit is contained in:
James Roseborough
2010-05-09 18:10:55 +00:00
parent 7c72a9feaf
commit 40b7cb19c9
36 changed files with 487 additions and 1444 deletions

View File

@@ -299,7 +299,7 @@ public class PackageLib extends OneArgFunction {
for ( int i=1; true; i++ ) {
LuaValue loader = tbl.get(i);
if ( loader.isnil() ) {
error( "module '"+name+"' not found: "+name+"\n"+sb );
error( "module '"+name+"' not found: "+name+sb );
}
/* call loader with module name as argument */

View File

@@ -1,34 +0,0 @@
package org.luaj;
import junit.framework.Test;
import junit.framework.TestSuite;
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("Test for org.luaj");
// debug tests
TestSuite vm = new TestSuite("VM");
vm.addTestSuite(org.luaj.vm.CompatibiltyTest.class);
vm.addTestSuite(org.luaj.vm.ErrorMessageTest.class);
vm.addTestSuite(org.luaj.vm.LuaStateTest.class);
vm.addTestSuite(org.luaj.vm.LoadStateTest.class);
vm.addTestSuite(org.luaj.vm.LStringTest.class);
vm.addTestSuite(org.luaj.vm.MathLibTest.class);
vm.addTestSuite(org.luaj.vm.LTableTest.class);
vm.addTestSuite(org.luaj.vm.LWeakTableTest.class);
suite.addTest(vm);
// compiler tests
TestSuite compiler = new TestSuite("Compiler");
compiler.addTestSuite(org.luaj.compiler.SimpleTests.class);
compiler.addTestSuite(org.luaj.compiler.RegressionTests.class);
compiler.addTestSuite(org.luaj.compiler.CompilerUnitTests.class);
compiler.addTestSuite(org.luaj.compiler.DumpLoadEndianIntTest.class);
suite.addTest(compiler);
return suite;
}
}

View File

@@ -1,11 +0,0 @@
package org.luaj;
import java.io.InputStream;
import org.luaj.platform.J2sePlatform;
public class TestPlatform extends J2sePlatform {
public InputStream openFile(String fileName) {
return getClass().getResourceAsStream("/" + fileName);
}
}

View File

@@ -1,44 +0,0 @@
package org.luaj.vm;
import java.io.IOException;
/**
* Test error messages produced by luaj.
*/
public class ErrorMessageTest extends ScriptDrivenTest {
private static final String dir = "src/test/errors";
public ErrorMessageTest() {
super(dir);
}
public void testBaseLibArgs() throws IOException, InterruptedException {
runTest("baselibargs");
}
public void testCoroutineLibArgs() throws IOException, InterruptedException {
runTest("coroutinelibargs");
}
public void testModuleLibArgs() throws IOException, InterruptedException {
runTest("modulelibargs");
}
public void testOperators() throws IOException, InterruptedException {
runTest("operators");
}
public void testStringLibArgs() throws IOException, InterruptedException {
runTest("stringlibargs");
}
public void testTableLibArgs() throws IOException, InterruptedException {
runTest("tablelibargs");
}
public void testMathLibArgs() throws IOException, InterruptedException {
runTest("mathlibargs");
}
}

View File

@@ -1,319 +0,0 @@
package org.luaj.vm;
import java.util.Vector;
import junit.framework.TestCase;
public class LTableTest extends TestCase {
protected LTable new_LTable() {
return new LTable();
}
protected LTable new_LTable(int n,int m) {
return new LTable(n,m);
}
public void testInOrderIntegerKeyInsertion() {
LTable t = new_LTable();
for ( int i = 1; i <= 32; ++i ) {
t.put( i, new LString( "Test Value! "+i ) );
}
// Ensure all keys are still there.
for ( int i = 1; i <= 32; ++i ) {
assertEquals( "Test Value! " + i, t.get( i ).toJavaString() );
}
// Ensure capacities make sense
assertEquals( 0, t.getHashCapacity() );
assertTrue( t.getArrayCapacity() >= 32 );
assertTrue( t.getArrayCapacity() <= 64 );
}
public void testResize() {
LTable t = new_LTable();
// NOTE: This order of insertion is important.
t.put(3, LInteger.valueOf(3));
t.put(1, LInteger.valueOf(1));
t.put(5, LInteger.valueOf(5));
t.put(4, LInteger.valueOf(4));
t.put(6, LInteger.valueOf(6));
t.put(2, LInteger.valueOf(2));
for ( int i = 1; i < 6; ++i ) {
assertEquals(LInteger.valueOf(i), t.get(i));
}
assertTrue( t.getArrayCapacity() >= 0 && t.getArrayCapacity() <= 2 );
assertTrue( t.getHashCapacity() >= 4 );
}
public void testOutOfOrderIntegerKeyInsertion() {
LTable t = new_LTable();
for ( int i = 32; i > 0; --i ) {
t.put( i, new LString( "Test Value! "+i ) );
}
// Ensure all keys are still there.
for ( int i = 1; i <= 32; ++i ) {
assertEquals( "Test Value! "+i, t.get( i ).toJavaString() );
}
// Ensure capacities make sense
assertTrue( t.getArrayCapacity() >= 0 );
assertTrue( t.getArrayCapacity() <= 6 );
assertTrue( t.getHashCapacity() >= 16 );
assertTrue( t.getHashCapacity() <= 64 );
}
public void testStringAndIntegerKeys() {
LTable t = new_LTable();
for ( int i = 0; i < 10; ++i ) {
LString str = new LString( String.valueOf( i ) );
t.put( i, str );
t.put( str, LInteger.valueOf( i ) );
}
assertTrue( t.getArrayCapacity() >= 9 ); // 1, 2, ..., 9
assertTrue( t.getArrayCapacity() <= 18 );
assertTrue( t.getHashCapacity() >= 11 ); // 0, "0", "1", ..., "9"
assertTrue( t.getHashCapacity() <= 33 );
LValue[] keys = t.getKeys();
int intKeys = 0;
int stringKeys = 0;
assertEquals( 20, keys.length );
for ( int i = 0; i < keys.length; ++i ) {
LValue k = keys[i];
if ( k instanceof LInteger ) {
final int ik = k.toJavaInt();
assertTrue( ik >= 0 && ik < 10 );
final int mask = 1 << ik;
assertTrue( ( intKeys & mask ) == 0 );
intKeys |= mask;
} else if ( k instanceof LString ) {
final int ik = Integer.parseInt( k.luaAsString().toJavaString() );
assertEquals( String.valueOf( ik ), k.luaAsString().toJavaString() );
assertTrue( ik >= 0 && ik < 10 );
final int mask = 1 << ik;
assertTrue( "Key \""+ik+"\" found more than once", ( stringKeys & mask ) == 0 );
stringKeys |= mask;
} else {
fail( "Unexpected type of key found" );
}
}
assertEquals( 0x03FF, intKeys );
assertEquals( 0x03FF, stringKeys );
}
public void testBadInitialCapacity() {
LTable t = new_LTable(0, 1);
t.put( "test", new LString("foo") );
t.put( "explode", new LString("explode") );
assertEquals( 2, t.size() );
}
public void testRemove0() {
LTable t = new_LTable(2, 0);
t.put( 1, new LString("foo") );
t.put( 2, new LString("bah") );
assertNotSame(LNil.NIL, t.get(1));
assertNotSame(LNil.NIL, t.get(2));
assertEquals(LNil.NIL, t.get(3));
t.put( 1, LNil.NIL );
t.put( 2, LNil.NIL );
t.put( 3, LNil.NIL );
assertEquals(LNil.NIL, t.get(1));
assertEquals(LNil.NIL, t.get(2));
assertEquals(LNil.NIL, t.get(3));
}
public void testRemove1() {
LTable t = new_LTable(0, 1);
t.put( "test", new LString("foo") );
t.put( "explode", LNil.NIL );
t.put( 42, LNil.NIL );
t.put( new_LTable(), LNil.NIL );
t.put( "test", LNil.NIL );
assertEquals( 0, t.size() );
t.put( 10, LInteger.valueOf( 5 ) );
t.put( 10, LNil.NIL );
assertEquals( 0, t.size() );
}
public void testRemove2() {
LTable t = new_LTable(0, 1);
t.put( "test", new LString("foo") );
t.put( "string", LInteger.valueOf( 10 ) );
assertEquals( 2, t.size() );
t.put( "string", LNil.NIL );
t.put( "three", new LDouble( 3.14 ) );
assertEquals( 2, t.size() );
t.put( "test", LNil.NIL );
assertEquals( 1, t.size() );
t.put( 10, LInteger.valueOf( 5 ) );
assertEquals( 2, t.size() );
t.put( 10, LNil.NIL );
assertEquals( 1, t.size() );
t.put( "three", LNil.NIL );
assertEquals( 0, t.size() );
}
public void testInOrderLuaLength() {
LTable t = new_LTable();
for ( int i = 1; i <= 32; ++i ) {
t.put( i, new LString( "Test Value! "+i ) );
assertEquals( i, t.luaLength() );
assertEquals( i, t.luaMaxN().toJavaInt() );
}
}
public void testOutOfOrderLuaLength() {
LTable t = new_LTable();
for ( int j=8; j<32; j+=8 ) {
for ( int i = j; i > 0; --i ) {
t.put( i, new LString( "Test Value! "+i ) );
}
assertEquals( j, t.luaLength() );
assertEquals( j, t.luaMaxN().toJavaInt() );
}
}
public void testStringKeysLuaLength() {
LTable t = new_LTable();
for ( int i = 1; i <= 32; ++i ) {
t.put( "str-"+i, new LString( "String Key Test Value! "+i ) );
assertEquals( 0, t.luaLength() );
assertEquals( 0, t.luaMaxN().toJavaInt() );
}
}
public void testMixedKeysLuaLength() {
LTable t = new_LTable();
for ( int i = 1; i <= 32; ++i ) {
t.put( "str-"+i, new LString( "String Key Test Value! "+i ) );
t.put( i, new LString( "Int Key Test Value! "+i ) );
assertEquals( i, t.luaLength() );
assertEquals( i, t.luaMaxN().toJavaInt() );
}
}
private static final void compareLists(LTable t,Vector v) {
int n = v.size();
assertEquals(v.size(),t.luaLength());
for ( int j=0; j<n; j++ ) {
Object vj = v.elementAt(j);
Object tj = t.get(j+1).toJavaString();
vj = ((LString)vj).toJavaString();
assertEquals(vj,tj);
}
}
public void testInsertBeginningOfList() {
LTable t = new_LTable();
Vector v = new Vector();
for ( int i = 1; i <= 32; ++i ) {
LString test = new LString("Test Value! "+i);
t.luaInsertPos(1, test);
v.insertElementAt(test, 0);
compareLists(t,v);
}
}
public void testInsertEndOfList() {
LTable t = new_LTable();
Vector v = new Vector();
for ( int i = 1; i <= 32; ++i ) {
LString test = new LString("Test Value! "+i);
t.luaInsertPos(0, test);
v.insertElementAt(test, v.size());
compareLists(t,v);
}
}
public void testInsertMiddleOfList() {
LTable t = new_LTable();
Vector v = new Vector();
for ( int i = 1; i <= 32; ++i ) {
LString test = new LString("Test Value! "+i);
int m = i / 2;
t.luaInsertPos(m+1, test);
v.insertElementAt(test, m);
compareLists(t,v);
}
}
private static final void prefillLists(LTable t,Vector v) {
for ( int i = 1; i <= 32; ++i ) {
LString test = new LString("Test Value! "+i);
t.luaInsertPos(0, test);
v.insertElementAt(test, v.size());
}
}
public void testRemoveBeginningOfList() {
LTable t = new_LTable();
Vector v = new Vector();
prefillLists(t,v);
for ( int i = 1; i <= 32; ++i ) {
t.luaRemovePos(1);
v.removeElementAt(0);
compareLists(t,v);
}
}
public void testRemoveEndOfList() {
LTable t = new_LTable();
Vector v = new Vector();
prefillLists(t,v);
for ( int i = 1; i <= 32; ++i ) {
t.luaRemovePos(0);
v.removeElementAt(v.size()-1);
compareLists(t,v);
}
}
public void testRemoveMiddleOfList() {
LTable t = new_LTable();
Vector v = new Vector();
prefillLists(t,v);
for ( int i = 1; i <= 32; ++i ) {
int m = v.size() / 2;
t.luaRemovePos(m+1);
v.removeElementAt(m);
compareLists(t,v);
}
}
}

View File

@@ -1,108 +0,0 @@
package org.luaj.vm;
import java.util.Random;
import org.luaj.vm.LNil;
import org.luaj.vm.LString;
import org.luaj.vm.LValue;
public class LWeakTableTest extends LTableTest {
protected LTable new_LTable() {
return new LWeakTable();
}
protected LTable new_LTable(int n,int m) {
return new LWeakTable(n,m);
}
Random random = new Random(0);
Runtime rt = Runtime.getRuntime();
protected void setUp() throws Exception {
super.setUp();
Runtime rt = Runtime.getRuntime();
rt.gc();
Thread.sleep(20);
rt.gc();
Thread.sleep(20);
}
private void runTest(int n,int i0,int i1,int di) {
System.out.println("------- testing "+n+" keys up to "+i1+" bytes each ("+(n*i1)+" bytes total)");
LTable t = new LWeakTable();
for ( int i=0; i<n; i++ )
t.put(i, new LString(new byte[1]));
for ( int i=i0; i<=i1; i+=di ) {
int hits = 0;
for ( int j=0; j<100; j++ ) {
int k = random.nextInt(n);
LValue v = t.get(k);
if ( v != LNil.NIL )
hits++;
t.put(i, new LString(new byte[i]));
}
long total = rt.totalMemory() / 1000;
long free = rt.freeMemory() / 1000;
long used = (rt.totalMemory() - rt.freeMemory()) / 1000;
System.out.println("keys="+n+" bytes="+i+" mem u(f,t)="+used+"("+free+"/"+total+") hits="+hits+"/100");
}
}
public void testWeakTable5000() {
runTest(100,0,5000,500);
}
public void testWeakTable10000() {
runTest(100,0,10000,1000);
}
public void testWeakTable100() {
runTest(100,0,100,10);
}
public void testWeakTable1000() {
runTest(100,0,1000,100);
}
public void testWeakTable2000() {
runTest(100,0,2000,200);
}
public void testWeakTableRehashToEmpty() {
LTable t = new_LTable();
Object obj = new Object();
LTable tableValue = new LTable();
LString stringValue = LString.valueOf("this is a test");
t.put("table", tableValue);
t.put("userdata", new LUserData(obj, null));
t.put("string", stringValue);
t.put("string2", LString.valueOf("another string"));
assertTrue("table must have at least 4 elements", t.hashKeys.length > 4);
System.gc();
assertTrue("table must have at least 4 elements", t.hashKeys.length > 4);
assertEquals(tableValue, t.get(LString.valueOf("table")));
assertEquals(stringValue, t.get(LString.valueOf("string")));
assertEquals(obj, t.get(LString.valueOf("userdata")).toJavaInstance());
obj = null;
tableValue = null;
stringValue = null;
// Garbage collection should cause weak entries to be dropped.
System.gc();
// Add a new key to cause a rehash - note that this causes the test to
// be dependent on the load factor, which is an implementation detail.
t.put("newkey1", 1);
// Removing the new key should leave the table empty since first set of values fell out
t.put("newkey1", LNil.NIL);
assertTrue("weak table must be empty", t.hashKeys.length == 0);
}
}

View File

@@ -1,122 +0,0 @@
package org.luaj.vm;
import java.util.Random;
import org.luaj.vm.LDouble;
import org.luaj.vm.LInteger;
import org.luaj.vm.LNumber;
import org.luaj.vm.LoadState;
import junit.framework.TestCase;
public class LoadStateTest extends TestCase {
double[] DOUBLE_VALUES = {
0.0,
1.0,
2.5,
10.0,
16.0,
16.125,
-1.0,
2.0,
-2.0,
-10.0,
-0.25,
-25,
Integer.MAX_VALUE,
Integer.MAX_VALUE - 1,
(double)Integer.MAX_VALUE + 1.0,
Integer.MIN_VALUE,
Integer.MIN_VALUE + 1,
(double)Integer.MIN_VALUE - 1.0,
Double.NEGATIVE_INFINITY,
Double.POSITIVE_INFINITY,
Double.MAX_VALUE,
Double.MAX_VALUE
};
public void testLongBitsToLuaNumber() {
for ( int i = 0; i < DOUBLE_VALUES.length; ++i ) {
double v = DOUBLE_VALUES[i];
long bits = Double.doubleToLongBits( v );
LNumber luaNumber = LoadState.longBitsToLuaNumber( bits );
assertEquals( v, luaNumber.toJavaDouble(), 0 );
if ( v != Integer.MIN_VALUE ) {
// Special case of MIN_VALUE is probably not worth dealing with.
// (Unlike zero, which is also a special case but much more common.)
assertEquals( "Value "+v+" (at index "+i+") can be represented as integer but was not",
luaNumber instanceof LInteger, v == (double)( (int) v ) );
}
}
}
private LNumber simpleBitsToLuaNumber( long bits ) {
double value = Double.longBitsToDouble( bits );
return LDouble.numberOf(value);
}
public void testLongBitsToLuaNumberSpeed() throws InterruptedException {
long[] BITS = new long[ 500000 ];
Random r = new Random();
for ( int i = 0; i < DOUBLE_VALUES.length; ++i ) {
BITS[i] = Double.doubleToLongBits( DOUBLE_VALUES[i] );
}
for ( int i = DOUBLE_VALUES.length; i < BITS.length; i += 2 ) {
BITS[i ] = r.nextLong();
BITS[i+1] = Double.doubleToLongBits( r.nextDouble() );
}
long simpleConversionCount = 0;
long complexConversionCount = 0;
collectGarbage();
long startTime = leadingEdgeTime();
long endTime = startTime + 1000;
int count = 0;
int n = BITS.length;
for ( ; currentTime()<endTime; count++ ) {
for ( int j=0; j<n; j++ )
simpleBitsToLuaNumber( BITS[j] );
}
simpleConversionCount += count;
collectGarbage();
startTime = leadingEdgeTime();
endTime = startTime + 1000;
count = 0;
for ( ; currentTime()<endTime; count++ ) {
for ( int j=0; j<n; j++ )
LoadState.longBitsToLuaNumber( BITS[j] );
}
complexConversionCount += count;
System.out.println("conversion counts: simple,complex="
+simpleConversionCount+","+complexConversionCount);
assertTrue( complexConversionCount >= simpleConversionCount );
}
private void collectGarbage() throws InterruptedException {
Runtime rt = Runtime.getRuntime();
rt.gc();
Thread.sleep(20);
rt.gc();
Thread.sleep(20);
}
private static long leadingEdgeTime() {
long s,e = currentTime();
for ( s=currentTime(); s==(e=currentTime()); )
;
return e;
}
private static long currentTime() {
return System.currentTimeMillis();
}
}

View File

@@ -1,62 +0,0 @@
package org.luaj.vm;
import java.io.IOException;
import junit.framework.TestCase;
import org.luaj.TestPlatform;
public class LuaStateTest extends TestCase {
LuaState vm;
protected void setUp() throws Exception {
Platform.setInstance(new TestPlatform());
vm = Platform.newLuaState();
}
public void testPushnilReplaceSettop() throws IOException {
vm.pushnil();
vm.replace(1);
vm.settop(1);
assertEquals( 1, vm.gettop() );
assertEquals( LNil.NIL, vm.topointer(1) );
assertEquals( LNil.NIL, vm.topointer(-1) );
}
public void testFuncCall() throws IOException {
vm.pushstring("bogus");
vm.pushfunction(new SomeFunc( "arg" ));
vm.pushstring("arg");
vm.call(1, 1);
assertEquals( 2, vm.gettop() );
assertEquals( "bogus", vm.tostring(1) );
assertEquals( LNil.NIL, vm.topointer(2) );
assertEquals( LNil.NIL, vm.topointer(-1) );
}
public void testFuncCall2() throws IOException {
vm.pushstring("bogus");
vm.pushfunction(new SomeFunc( "nil" ));
vm.call(0, 1);
assertEquals( 2, vm.gettop() );
assertEquals( "bogus", vm.tostring(1) );
assertEquals( LNil.NIL, vm.topointer(2) );
assertEquals( LNil.NIL, vm.topointer(-1) );
}
private static final class SomeFunc extends LFunction {
private String expected;
public SomeFunc(String expected) {
this.expected = expected;
}
public boolean luaStackCall(LuaState vm) {
String arg = vm.tostring(2);
assertEquals(expected, arg);
vm.pushnil();
vm.replace(1);
vm.settop(1);
return false;
}
}
}

View File

@@ -1,242 +0,0 @@
package org.luaj.vm;
import junit.framework.TestCase;
import org.luaj.lib.MathLib;
import org.luaj.platform.J2meMidp20Cldc11Platform;
import org.luaj.platform.J2sePlatform;
public class MathLibTest extends TestCase {
private Platform j2se;
private Platform j2me;
private boolean supportedOnJ2me;
protected void setUp() throws Exception {
j2se = new J2sePlatform();
j2me = new org.luaj.platform.J2meMidp20Cldc11Platform(null);
supportedOnJ2me = true;
}
public void testMathDPow() {
assertEquals( 1, J2meMidp20Cldc11Platform.dpow(2, 0), 0 );
assertEquals( 2, J2meMidp20Cldc11Platform.dpow(2, 1), 0 );
assertEquals( 8, J2meMidp20Cldc11Platform.dpow(2, 3), 0 );
assertEquals( -8, J2meMidp20Cldc11Platform.dpow(-2, 3), 0 );
assertEquals( 1/8., J2meMidp20Cldc11Platform.dpow(2, -3), 0 );
assertEquals( -1/8., J2meMidp20Cldc11Platform.dpow(-2, -3), 0 );
assertEquals( 16, J2meMidp20Cldc11Platform.dpow(256, .5), 0 );
assertEquals( 4, J2meMidp20Cldc11Platform.dpow(256, .25), 0 );
assertEquals( 64, J2meMidp20Cldc11Platform.dpow(256, .75), 0 );
assertEquals( 1./16, J2meMidp20Cldc11Platform.dpow(256, - .5), 0 );
assertEquals( 1./ 4, J2meMidp20Cldc11Platform.dpow(256, -.25), 0 );
assertEquals( 1./64, J2meMidp20Cldc11Platform.dpow(256, -.75), 0 );
assertEquals( Double.NaN, J2meMidp20Cldc11Platform.dpow(-256, .5), 0 );
assertEquals( 1, J2meMidp20Cldc11Platform.dpow(.5, 0), 0 );
assertEquals( .5, J2meMidp20Cldc11Platform.dpow(.5, 1), 0 );
assertEquals(.125, J2meMidp20Cldc11Platform.dpow(.5, 3), 0 );
assertEquals( 2, J2meMidp20Cldc11Platform.dpow(.5, -1), 0 );
assertEquals( 8, J2meMidp20Cldc11Platform.dpow(.5, -3), 0 );
assertEquals(1, J2meMidp20Cldc11Platform.dpow(0.0625, 0), 0 );
assertEquals(0.00048828125, J2meMidp20Cldc11Platform.dpow(0.0625, 2.75), 0 );
}
public void testAbs() {
tryMathOp( MathLib.ABS, 23.45 );
tryMathOp( MathLib.ABS, -23.45 );
}
public void testCos() {
tryTrigOps( MathLib.COS );
}
public void testCosh() {
supportedOnJ2me = false;
tryTrigOps( MathLib.COSH );
}
public void testDeg() {
tryTrigOps( MathLib.DEG );
}
public void testExp() {
supportedOnJ2me = false;
tryMathOp( MathLib.EXP, 0 );
tryMathOp( MathLib.EXP, 0.1 );
tryMathOp( MathLib.EXP, .9 );
tryMathOp( MathLib.EXP, 1. );
tryMathOp( MathLib.EXP, 9 );
tryMathOp( MathLib.EXP, -.1 );
tryMathOp( MathLib.EXP, -.9 );
tryMathOp( MathLib.EXP, -1. );
tryMathOp( MathLib.EXP, -9 );
}
public void testLog() {
supportedOnJ2me = false;
tryMathOp( MathLib.LOG, 0.1 );
tryMathOp( MathLib.LOG, .9 );
tryMathOp( MathLib.LOG, 1. );
tryMathOp( MathLib.LOG, 9 );
tryMathOp( MathLib.LOG, -.1 );
tryMathOp( MathLib.LOG, -.9 );
tryMathOp( MathLib.LOG, -1. );
tryMathOp( MathLib.LOG, -9 );
}
public void testLog10() {
supportedOnJ2me = false;
tryMathOp( MathLib.LOG10, 0.1 );
tryMathOp( MathLib.LOG10, .9 );
tryMathOp( MathLib.LOG10, 1. );
tryMathOp( MathLib.LOG10, 9 );
tryMathOp( MathLib.LOG10, 10 );
tryMathOp( MathLib.LOG10, 100 );
tryMathOp( MathLib.LOG10, -.1 );
tryMathOp( MathLib.LOG10, -.9 );
tryMathOp( MathLib.LOG10, -1. );
tryMathOp( MathLib.LOG10, -9 );
tryMathOp( MathLib.LOG10, -10 );
tryMathOp( MathLib.LOG10, -100 );
}
public void testRad() {
tryMathOp( MathLib.RAD, 0 );
tryMathOp( MathLib.RAD, 0.1 );
tryMathOp( MathLib.RAD, .9 );
tryMathOp( MathLib.RAD, 1. );
tryMathOp( MathLib.RAD, 9 );
tryMathOp( MathLib.RAD, 10 );
tryMathOp( MathLib.RAD, 100 );
tryMathOp( MathLib.RAD, -.1 );
tryMathOp( MathLib.RAD, -.9 );
tryMathOp( MathLib.RAD, -1. );
tryMathOp( MathLib.RAD, -9 );
tryMathOp( MathLib.RAD, -10 );
tryMathOp( MathLib.RAD, -100 );
}
public void testSin() {
tryTrigOps( MathLib.SIN );
}
public void testSinh() {
supportedOnJ2me = false;
tryTrigOps( MathLib.SINH );
}
public void testSqrt() {
tryMathOp( MathLib.SQRT, 0 );
tryMathOp( MathLib.SQRT, 0.1 );
tryMathOp( MathLib.SQRT, .9 );
tryMathOp( MathLib.SQRT, 1. );
tryMathOp( MathLib.SQRT, 9 );
tryMathOp( MathLib.SQRT, 10 );
tryMathOp( MathLib.SQRT, 100 );
}
public void testTan() {
tryTrigOps( MathLib.TAN );
}
public void testTanh() {
supportedOnJ2me = false;
tryTrigOps( MathLib.TANH );
}
public void testAtan2() {
supportedOnJ2me = false;
tryDoubleOps( MathLib.ATAN2, false );
}
public void testFmod() {
tryDoubleOps( MathLib.FMOD, false );
}
public void testPow() {
tryDoubleOps( MathLib.POW, true );
}
private void tryDoubleOps( int id, boolean positiveOnly ) {
// y>0, x>0
tryMathOp( id, 0.1, 4.0 );
tryMathOp( id, .9, 4.0 );
tryMathOp( id, 1., 4.0 );
tryMathOp( id, 9, 4.0 );
tryMathOp( id, 10, 4.0 );
tryMathOp( id, 100, 4.0 );
// y>0, x<0
tryMathOp( id, 0.1, -4.0 );
tryMathOp( id, .9, -4.0 );
tryMathOp( id, 1., -4.0 );
tryMathOp( id, 9, -4.0 );
tryMathOp( id, 10, -4.0 );
tryMathOp( id, 100, -4.0 );
if ( ! positiveOnly ) {
// y<0, x>0
tryMathOp( id, -0.1, 4.0 );
tryMathOp( id, -.9, 4.0 );
tryMathOp( id, -1., 4.0 );
tryMathOp( id, -9, 4.0 );
tryMathOp( id, -10, 4.0 );
tryMathOp( id, -100, 4.0 );
// y<0, x<0
tryMathOp( id, -0.1, -4.0 );
tryMathOp( id, -.9, -4.0 );
tryMathOp( id, -1., -4.0 );
tryMathOp( id, -9, -4.0 );
tryMathOp( id, -10, -4.0 );
tryMathOp( id, -100, -4.0 );
}
// degenerate cases
tryMathOp( id, 0, 1 );
tryMathOp( id, 1, 0 );
tryMathOp( id, -1, 0 );
tryMathOp( id, 0, -1 );
tryMathOp( id, 0, 0 );
}
private void tryTrigOps(int id) {
tryMathOp( id, 0 );
tryMathOp( id, Math.PI/8 );
tryMathOp( id, Math.PI*7/8 );
tryMathOp( id, Math.PI*8/8 );
tryMathOp( id, Math.PI*9/8 );
tryMathOp( id, -Math.PI/8 );
tryMathOp( id, -Math.PI*7/8 );
tryMathOp( id, -Math.PI*8/8 );
tryMathOp( id, -Math.PI*9/8 );
}
private void tryMathOp(int id, double x) {
try {
double expected = j2se.mathop(id, LDouble.valueOf(x)).toJavaDouble();
double actual = j2me.mathop(id, LDouble.valueOf(x)).toJavaDouble();
if ( supportedOnJ2me )
assertEquals( expected, actual, 1.e-5 );
else
this.fail("j2me should throw exception for math op "+id+" but returned "+actual);
} catch ( LuaErrorException lee ) {
if ( supportedOnJ2me )
throw lee;
}
}
private void tryMathOp(int id, double a, double b) {
try {
double expected = j2se.mathop(id, LDouble.numberOf(a), LDouble.numberOf(b)).toJavaDouble();
double actual = j2me.mathop(id, LDouble.numberOf(a), LDouble.numberOf(b)).toJavaDouble();
if ( supportedOnJ2me )
assertEquals( expected, actual, 1.e-5 );
else
this.fail("j2me should throw exception for math op "+id+" but returned "+actual);
} catch ( LuaErrorException lee ) {
if ( supportedOnJ2me )
throw lee;
}
}
}

View File

@@ -1,194 +0,0 @@
package org.luaj.vm;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import junit.framework.TestCase;
import org.luaj.compiler.LuaC;
import org.luaj.lib.BaseLib;
import org.luaj.lib.DebugLib;
import org.luaj.platform.J2sePlatform;
abstract
public class ScriptDrivenTest extends TestCase {
private final String basedir;
protected ScriptDrivenTest( String directory ) {
basedir = directory;
}
// */
protected void runTest(String testName) throws IOException,
InterruptedException {
// set platform relative to directory
Platform.setInstance(new J2sePlatform());
// new lua state
LuaState state = Platform.newLuaState();
// install the compiler
LuaC.install();
// install debug lib
DebugLib.install( state );
// load the file
LPrototype p = loadScript(state, testName);
p.source = LString.valueOf("stdin");
// Replace System.out with a ByteArrayOutputStream
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
BaseLib.redirectOutput(outputStream);
try {
// create closure and execute
LClosure c = p.newClosure(state._G);
state.pushlvalue(c);
state.call(0, 0);
final String actualOutput = new String(outputStream.toByteArray());
final String expectedOutput = getExpectedOutput(testName);
assertEquals(expectedOutput, actualOutput);
} finally {
BaseLib.restoreStandardOutput();
outputStream.close();
}
}
protected LPrototype loadScript(LuaState state, String name)
throws IOException {
File file = new File(basedir+"/"+name+".luac");
if ( !file.exists() )
file = new File(basedir+"/"+name+".lua");
if ( !file.exists() )
fail("Could not load script for test case: " + name);
InputStream script = new FileInputStream(file);
try {
// Use "stdin" instead of resource name so that output matches
// standard Lua.
return LoadState.undump(state, script, "stdin");
} finally {
script.close();
}
}
private String getExpectedOutput(final String name) throws IOException,
InterruptedException {
String expectedOutputName = basedir+"/"+name+"-expected.out";
File file = new File( expectedOutputName );
if ( file.exists() ) {
InputStream is = new FileInputStream(file);
try {
return readString(is);
} finally {
is.close();
}
} else {
file = new File(basedir+"/"+name+".lua");
if ( !file.exists() )
fail("Could not load script for test case: " + name);
InputStream script = new FileInputStream(file);
// }
try {
String luaCommand = System.getProperty("LUA_COMMAND");
if ( luaCommand == null )
luaCommand = "lua";
return collectProcessOutput(new String[] { luaCommand, "-" }, script);
} finally {
script.close();
}
}
}
private String collectProcessOutput(String[] cmd, final InputStream input)
throws IOException, InterruptedException {
Runtime r = Runtime.getRuntime();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final Process p = r.exec(cmd);
try {
// start a thread to write the given input to the subprocess.
Thread inputCopier = (new Thread() {
public void run() {
try {
OutputStream processStdIn = p.getOutputStream();
try {
copy(input, processStdIn);
} finally {
processStdIn.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
inputCopier.start();
// start another thread to read output from the subprocess.
Thread outputCopier = (new Thread() {
public void run() {
try {
InputStream processStdOut = p.getInputStream();
try {
copy(processStdOut, baos);
} finally {
processStdOut.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
});
outputCopier.start();
// start another thread to read output from the subprocess.
Thread errorCopier = (new Thread() {
public void run() {
try {
InputStream processError = p.getErrorStream();
try {
copy(processError, System.err);
} finally {
processError.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
});
errorCopier.start();
p.waitFor();
inputCopier.join();
outputCopier.join();
errorCopier.join();
return new String(baos.toByteArray());
} finally {
p.destroy();
}
}
private String readString(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
copy(is, baos);
return new String(baos.toByteArray());
}
private void copy(InputStream is, OutputStream os) throws IOException {
byte[] buf = new byte[1024];
int r;
while ((r = is.read(buf)) >= 0) {
os.write(buf, 0, r);
}
}
}

View File

@@ -1,123 +0,0 @@
package org.luaj.vm;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.luaj.TestPlatform;
import org.luaj.lib.BaseLib;
public class StandardTest extends TestCase {
public static Test suite() throws IOException {
ZipEntry file;
final HashMap tests = new HashMap();
final HashMap results = new HashMap();
InputStream zipStream = StandardTest.class.getResourceAsStream( "/standard-tests.zip" );
ZipInputStream testSuiteArchive = new ZipInputStream( zipStream );
try {
while ( ( file = testSuiteArchive.getNextEntry() ) != null ) {
final String entryName = file.getName();
if ( entryName.endsWith( ".luac" ) ) {
LPrototype p = LoadState.undump( new LuaState(), testSuiteArchive, entryName );
tests.put( entryName.substring( 0, entryName.length() - 5 ), p );
} else if ( entryName.endsWith( ".out" ) ) {
results.put( entryName.substring( 0, entryName.length() - 4 ), readString( testSuiteArchive ) );
}
}
} finally {
testSuiteArchive.close();
}
TestSuite suite = new TestSuite();
for ( Iterator keys = tests.keySet().iterator(); keys.hasNext(); ) {
String test = (String)keys.next();
final LPrototype code = (LPrototype)tests.get( test );
final String expectedResult = (String)results.get( test );
if ( code != null && expectedResult != null ) {
suite.addTest( new StandardTest( test, code, expectedResult ) );
}
}
return suite;
}
private final LPrototype code;
private final String expectedResult;
public StandardTest( String name, LPrototype code, String expectedResult ) {
super( name );
this.code = code;
this.expectedResult = expectedResult;
}
public void runTest() {
Platform.setInstance(new TestPlatform());
LuaState state = Platform.newLuaState();
// hack: it's unpleasant when the test cases fail to terminate;
// unfortunately, there is a test in the standard suite that
// relies on weak tables having their elements removed by
// the garbage collector. Until we implement that, remove the
// built-in collectgarbage function.
state._G.put( "collectgarbage", LNil.NIL );
LClosure c = code.newClosure( state._G );
ByteArrayOutputStream output = new ByteArrayOutputStream();
BaseLib.redirectOutput( output );
try {
try {
state.doCall( c, new LValue[0] );
} catch ( RuntimeException exn ) {
final int ncalls = Math.min( state.calls.length, state.cc+1 );
StackTraceElement[] stackTrace = new StackTraceElement[ncalls];
for ( int i = 0; i < ncalls; ++i ) {
CallInfo call = state.calls[i];
LPrototype p = call.closure.p;
int line = p.lineinfo[call.pc-1];
String func = call.closure.luaAsString().toJavaString();
stackTrace[ncalls - i - 1] = new StackTraceElement(getName(), func, getName()+".lua", line );
}
RuntimeException newExn = new RuntimeException( exn );
newExn.setStackTrace( stackTrace );
newExn.printStackTrace();
throw newExn;
}
final String actualResult = new String( output.toByteArray() );
assertEquals( expectedResult, actualResult );
} finally {
BaseLib.restoreStandardOutput();
}
}
private static String readString( InputStream is ) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
copy( is, baos );
return new String( baos.toByteArray() );
}
private static void copy( InputStream is, OutputStream os ) throws IOException {
byte[] buf = new byte[ 1024 ];
int r;
while ( ( r = is.read( buf ) ) >= 0 ) {
os.write( buf, 0, r );
}
}
}

View File

@@ -1,19 +0,0 @@
package org.luaj.vm.require;
import org.luaj.vm.LuaState;
/**
* This should fail while trying to load via "require() because it is not an LFunction"
*
*/
public class RequireSampleClassCastExcep {
public RequireSampleClassCastExcep() {
}
public boolean luaStackCall( LuaState vm ) {
System.out.println("called "+this.getClass().getName()+" with vm.topointer(1)=="+vm.topointer(1) );
vm.resettop();
return false;
}
}

View File

@@ -1,20 +0,0 @@
package org.luaj.vm.require;
import org.luaj.vm.LFunction;
import org.luaj.vm.LuaState;
/**
* This should fail while trying to load via "require()" because it throws a LuaError
*
*/
public class RequireSampleLoadLuaError extends LFunction {
public RequireSampleLoadLuaError() {
}
public boolean luaStackCall( LuaState vm ) {
System.out.println("called "+this.getClass().getName()+" with vm.topointer(1)=="+vm.topointer(1) );
vm.error("lua error thrown by "+this.getClass().getName());
return false;
}
}

View File

@@ -1,19 +0,0 @@
package org.luaj.vm.require;
import org.luaj.vm.LFunction;
import org.luaj.vm.LuaState;
/**
* This should fail while trying to load via "require()" because it throws a RuntimeException
*
*/
public class RequireSampleLoadRuntimeExcep extends LFunction {
public RequireSampleLoadRuntimeExcep() {
}
public boolean luaStackCall( LuaState vm ) {
System.out.println("called "+this.getClass().getName()+" with vm.topointer(1)=="+vm.topointer(1) );
throw new RuntimeException("error thrown by "+this.getClass().getName());
}
}

View File

@@ -1,20 +0,0 @@
package org.luaj.vm.require;
import org.luaj.vm.LFunction;
import org.luaj.vm.LuaState;
/**
* This should succeed as a library that can be loaded dynmaically via "require()"
*
*/
public class RequireSampleSuccess extends LFunction {
public RequireSampleSuccess() {
}
public boolean luaStackCall( LuaState vm ) {
System.out.println("called "+this.getClass().getName()+" with vm.topointer(1)=="+vm.topointer(1) );
vm.resettop();
return false;
}
}

View File

@@ -1,91 +0,0 @@
-- The Computer Language Benchmarks Game
-- http://shootout.alioth.debian.org/
-- contributed by Mike Pall
-- modified by Rob Kendrick to be parallel
-- modified by Isaac Gouy
-- called with the following arguments on the command line;
-- 1: size of mandelbrot to generate
-- 2: number of children to spawn (defaults to 6, which works well on 4-way)
-- If this is a child, then there will be additional parameters;
-- 3: start row
-- 4: end row
--
-- Children buffer up their output and emit it to stdout when
-- finished, to avoid stalling due to a full pipe.
local width = tonumber(arg and arg[1]) or 100
local children = tonumber(arg and arg[2]) or 6
local srow = tonumber(arg and arg[3])
local erow = tonumber(arg and arg[4])
local height, wscale = width, 2/width
local m, limit2 = 50, 4.0
local write, char = io.write, string.char
if not srow then
-- we are the parent process. emit the header, and then spawn children
local workunit = math.floor(width / (children + 1))
local handles = { }
write("P4\n", width, " ", height, "\n")
children = children - 1
for i = 0, children do
local cs, ce
if i == 0 then
cs = 0
ce = workunit
elseif i == children then
cs = (workunit * i) + 1
ce = width - 1
else
cs = (workunit * i) + 1
ce = cs + workunit - 1
end
handles[i + 1] = io.popen(("%s %s %d %d %d %d"):format(
arg[-1], arg[0], width, children + 1, cs, ce))
end
-- collect answers, and emit
for i = 0, children do
write(handles[i + 1]:read "*a")
end
else
-- we are a child process. do the work allocated to us.
local obuff = { }
for y=srow,erow do
local Ci = 2*y / height - 1
for xb=0,width-1,8 do
local bits = 0
local xbb = xb+7
for x=xb,xbb < width and xbb or width-1 do
bits = bits + bits
local Zr, Zi, Zrq, Ziq = 0.0, 0.0, 0.0, 0.0
local Cr = x * wscale - 1.5
for i=1,m do
local Zri = Zr*Zi
Zr = Zrq - Ziq + Cr
Zi = Zri + Zri + Ci
Zrq = Zr*Zr
Ziq = Zi*Zi
if Zrq + Ziq > limit2 then
bits = bits + 1
break
end
end
end
if xbb >= width then
for x=width,xbb do bits = bits + bits + 1 end
end
obuff[#obuff + 1] = char(255 - bits)
end
end
write(table.concat(obuff))
end

View File

@@ -44,6 +44,7 @@ public class AllTests {
vm.addTestSuite(UnaryBinaryOperatorsTest.class);
vm.addTestSuite(MetatableTest.class);
vm.addTestSuite(LuaOperationsTest.class);
vm.addTestSuite(StringTest.class);
suite.addTest(vm);
// table tests
@@ -67,11 +68,14 @@ public class AllTests {
// library tests
TestSuite lib = new TestSuite("Library Tests");
lib.addTestSuite(LuaJavaCoercionTest.class);
lib.addTestSuite(RequireClassTest.class);
suite.addTest(lib);
// compatiblity tests
suite.addTest(CompatibiltyTest.suite());
suite.addTestSuite(Luajvm1CompatibilityTest.class);
TestSuite compat = (TestSuite) CompatibiltyTest.suite();
suite.addTest( compat );
compat.addTestSuite(ErrorsTest.class);
compat.addTestSuite(Luajvm1CompatibilityTest.class);
// luajc regression tests
TestSuite luajc = new TestSuite("Java Compiler Tests");

View File

@@ -0,0 +1,55 @@
/*******************************************************************************
* Copyright (c) 2009 Luaj.org. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
package org.luaj.vm2;
import org.luaj.vm2.compiler.LuaC;
/**
* Test argument type check errors
*
* Results are compared for exact match with
* the installed C-based lua environment.
*/
public class ErrorsTest extends ScriptDrivenTest {
private static final String dir = "test/lua/errors";
public ErrorsTest() {
super(ScriptDrivenTest.PlatformType.JSE, dir);
}
protected void setUp() throws Exception {
super.setUp();
LuaC.install();
}
public void testBaseLibArgs() { runTest("baselibargs"); }
public void testCoroutineLibArgs() { runTest("coroutinelibargs"); }
public void testIoLibArgs() { runTest("iolibargs"); }
public void testMathLibArgs() { runTest("mathlibargs"); }
public void testModuleLibArgs() { runTest("modulelibargs"); }
public void testOperators() { runTest("operators"); }
public void testStringLibArgs() { runTest("stringlibargs"); }
public void testTableLibArgs() { runTest("tablelibargs"); }
}

View File

@@ -0,0 +1,251 @@
package org.luaj.vm2;
import junit.framework.TestCase;
import org.luaj.vm2.lib.JsePlatform;
import org.luaj.vm2.lib.MathLib;
import org.luaj.vm2.lib.jse.JseMathLib;
public class MathLibTest extends TestCase {
private LuaValue j2se;
private LuaValue j2me;
private boolean supportedOnJ2me;
public MathLibTest() {
LuaValue g = JsePlatform.standardGlobals();
j2se = g.get("math");
g.load( new MathLib() );
j2me = g.get("math");
}
protected void setUp() throws Exception {
supportedOnJ2me = true;
}
public void testMathDPow() {
assertEquals( 1, j2mepow(2, 0), 0 );
assertEquals( 2, j2mepow(2, 1), 0 );
assertEquals( 8, j2mepow(2, 3), 0 );
assertEquals( -8, j2mepow(-2, 3), 0 );
assertEquals( 1/8., j2mepow(2, -3), 0 );
assertEquals( -1/8., j2mepow(-2, -3), 0 );
assertEquals( 16, j2mepow(256, .5), 0 );
assertEquals( 4, j2mepow(256, .25), 0 );
assertEquals( 64, j2mepow(256, .75), 0 );
assertEquals( 1./16, j2mepow(256, - .5), 0 );
assertEquals( 1./ 4, j2mepow(256, -.25), 0 );
assertEquals( 1./64, j2mepow(256, -.75), 0 );
assertEquals( Double.NaN, j2mepow(-256, .5), 0 );
assertEquals( 1, j2mepow(.5, 0), 0 );
assertEquals( .5, j2mepow(.5, 1), 0 );
assertEquals(.125, j2mepow(.5, 3), 0 );
assertEquals( 2, j2mepow(.5, -1), 0 );
assertEquals( 8, j2mepow(.5, -3), 0 );
assertEquals(1, j2mepow(0.0625, 0), 0 );
assertEquals(0.00048828125, j2mepow(0.0625, 2.75), 0 );
}
private double j2mepow(double x, double y) {
return j2me.get("pow").call(LuaValue.valueOf(x),LuaValue.valueOf(y)).todouble();
}
public void testAbs() {
tryMathOp( "abs", 23.45 );
tryMathOp( "abs", -23.45 );
}
public void testCos() {
tryTrigOps( "cos" );
}
public void testCosh() {
supportedOnJ2me = false;
tryTrigOps( "cosh" );
}
public void testDeg() {
tryTrigOps( "deg" );
}
public void testExp() {
//supportedOnJ2me = false;
tryMathOp( "exp", 0 );
tryMathOp( "exp", 0.1 );
tryMathOp( "exp", .9 );
tryMathOp( "exp", 1. );
tryMathOp( "exp", 9 );
tryMathOp( "exp", -.1 );
tryMathOp( "exp", -.9 );
tryMathOp( "exp", -1. );
tryMathOp( "exp", -9 );
}
public void testLog() {
supportedOnJ2me = false;
tryMathOp( "log", 0.1 );
tryMathOp( "log", .9 );
tryMathOp( "log", 1. );
tryMathOp( "log", 9 );
tryMathOp( "log", -.1 );
tryMathOp( "log", -.9 );
tryMathOp( "log", -1. );
tryMathOp( "log", -9 );
}
public void testLog10() {
supportedOnJ2me = false;
tryMathOp( "log10", 0.1 );
tryMathOp( "log10", .9 );
tryMathOp( "log10", 1. );
tryMathOp( "log10", 9 );
tryMathOp( "log10", 10 );
tryMathOp( "log10", 100 );
tryMathOp( "log10", -.1 );
tryMathOp( "log10", -.9 );
tryMathOp( "log10", -1. );
tryMathOp( "log10", -9 );
tryMathOp( "log10", -10 );
tryMathOp( "log10", -100 );
}
public void testRad() {
tryMathOp( "rad", 0 );
tryMathOp( "rad", 0.1 );
tryMathOp( "rad", .9 );
tryMathOp( "rad", 1. );
tryMathOp( "rad", 9 );
tryMathOp( "rad", 10 );
tryMathOp( "rad", 100 );
tryMathOp( "rad", -.1 );
tryMathOp( "rad", -.9 );
tryMathOp( "rad", -1. );
tryMathOp( "rad", -9 );
tryMathOp( "rad", -10 );
tryMathOp( "rad", -100 );
}
public void testSin() {
tryTrigOps( "sin" );
}
public void testSinh() {
supportedOnJ2me = false;
tryTrigOps( "sinh" );
}
public void testSqrt() {
tryMathOp( "sqrt", 0 );
tryMathOp( "sqrt", 0.1 );
tryMathOp( "sqrt", .9 );
tryMathOp( "sqrt", 1. );
tryMathOp( "sqrt", 9 );
tryMathOp( "sqrt", 10 );
tryMathOp( "sqrt", 100 );
}
public void testTan() {
tryTrigOps( "tan" );
}
public void testTanh() {
supportedOnJ2me = false;
tryTrigOps( "tanh" );
}
public void testAtan2() {
supportedOnJ2me = false;
tryDoubleOps( "atan2", false );
}
public void testFmod() {
tryDoubleOps( "fmod", false );
}
public void testPow() {
tryDoubleOps( "pow", true );
}
private void tryDoubleOps( String op, boolean positiveOnly ) {
// y>0, x>0
tryMathOp( op, 0.1, 4.0 );
tryMathOp( op, .9, 4.0 );
tryMathOp( op, 1., 4.0 );
tryMathOp( op, 9, 4.0 );
tryMathOp( op, 10, 4.0 );
tryMathOp( op, 100, 4.0 );
// y>0, x<0
tryMathOp( op, 0.1, -4.0 );
tryMathOp( op, .9, -4.0 );
tryMathOp( op, 1., -4.0 );
tryMathOp( op, 9, -4.0 );
tryMathOp( op, 10, -4.0 );
tryMathOp( op, 100, -4.0 );
if ( ! positiveOnly ) {
// y<0, x>0
tryMathOp( op, -0.1, 4.0 );
tryMathOp( op, -.9, 4.0 );
tryMathOp( op, -1., 4.0 );
tryMathOp( op, -9, 4.0 );
tryMathOp( op, -10, 4.0 );
tryMathOp( op, -100, 4.0 );
// y<0, x<0
tryMathOp( op, -0.1, -4.0 );
tryMathOp( op, -.9, -4.0 );
tryMathOp( op, -1., -4.0 );
tryMathOp( op, -9, -4.0 );
tryMathOp( op, -10, -4.0 );
tryMathOp( op, -100, -4.0 );
}
// degenerate cases
tryMathOp( op, 0, 1 );
tryMathOp( op, 1, 0 );
tryMathOp( op, -1, 0 );
tryMathOp( op, 0, -1 );
tryMathOp( op, 0, 0 );
}
private void tryTrigOps(String op) {
tryMathOp( op, 0 );
tryMathOp( op, Math.PI/8 );
tryMathOp( op, Math.PI*7/8 );
tryMathOp( op, Math.PI*8/8 );
tryMathOp( op, Math.PI*9/8 );
tryMathOp( op, -Math.PI/8 );
tryMathOp( op, -Math.PI*7/8 );
tryMathOp( op, -Math.PI*8/8 );
tryMathOp( op, -Math.PI*9/8 );
}
private void tryMathOp(String op, double x) {
try {
double expected = j2se.get(op).call( LuaValue.valueOf(x)).todouble();
double actual = j2me.get(op).call( LuaValue.valueOf(x)).todouble();
if ( supportedOnJ2me )
assertEquals( expected, actual, 1.e-4 );
else
fail("j2me should throw exception for math."+op+" but returned "+actual);
} catch ( LuaError lee ) {
if ( supportedOnJ2me )
throw lee;
}
}
private void tryMathOp(String op, double a, double b) {
try {
double expected = j2se.get(op).call( LuaValue.valueOf(a), LuaValue.valueOf(b)).todouble();
double actual = j2me.get(op).call( LuaValue.valueOf(a), LuaValue.valueOf(b)).todouble();
if ( supportedOnJ2me )
assertEquals( expected, actual, 1.e-5 );
else
fail("j2me should throw exception for math."+op+" but returned "+actual);
} catch ( LuaError lee ) {
if ( supportedOnJ2me )
throw lee;
}
}
}

View File

@@ -0,0 +1,84 @@
package org.luaj.vm2;
import junit.framework.TestCase;
import org.luaj.vm2.lib.JsePlatform;
import org.luaj.vm2.require.RequireSampleClassCastExcep;
import org.luaj.vm2.require.RequireSampleLoadLuaError;
import org.luaj.vm2.require.RequireSampleLoadRuntimeExcep;
public class RequireClassTest extends TestCase {
private LuaTable globals;
private LuaValue require;
public void setUp() {
globals = JsePlatform.standardGlobals();
require = globals.get("require");
}
public void testRequireClassSuccess() {
LuaValue result = require.call( LuaValue.valueOf("org.luaj.vm2.require.RequireSampleSuccess") );
assertEquals( "require-sample-success", result.tojstring() );
result = require.call( LuaValue.valueOf("org.luaj.vm2.require.RequireSampleSuccess") );
assertEquals( "require-sample-success", result.tojstring() );
}
public void testRequireClassLoadLuaError() {
try {
LuaValue result = require.call( LuaValue.valueOf(RequireSampleLoadLuaError.class.getName()) );
fail( "incorrectly loaded class that threw lua error");
} catch ( LuaError le ) {
assertEquals(
"sample-load-lua-error",
le.getMessage() );
}
try {
LuaValue result = require.call( LuaValue.valueOf(RequireSampleLoadLuaError.class.getName()) );
fail( "incorrectly loaded class that threw lua error");
} catch ( LuaError le ) {
assertEquals(
"loop or previous error loading module '"+RequireSampleLoadLuaError.class.getName()+"'",
le.getMessage() );
}
}
public void testRequireClassLoadRuntimeException() {
try {
LuaValue result = require.call( LuaValue.valueOf(RequireSampleLoadRuntimeExcep.class.getName()) );
fail( "incorrectly loaded class that threw runtime exception");
} catch ( RuntimeException le ) {
assertEquals(
"sample-load-runtime-exception",
le.getMessage() );
}
try {
LuaValue result = require.call( LuaValue.valueOf(RequireSampleLoadRuntimeExcep.class.getName()) );
fail( "incorrectly loaded class that threw runtime exception");
} catch ( LuaError le ) {
assertEquals(
"loop or previous error loading module '"+RequireSampleLoadRuntimeExcep.class.getName()+"'",
le.getMessage() );
}
}
public void testRequireClassClassCastException() {
try {
LuaValue result = require.call( LuaValue.valueOf(RequireSampleClassCastExcep.class.getName()) );
fail( "incorrectly loaded class that threw class cast exception");
} catch ( LuaError le ) {
String msg = le.getMessage();
if ( msg.indexOf("not found") < 0 )
fail( "expected 'not found' message but got "+msg );
}
try {
LuaValue result = require.call( LuaValue.valueOf(RequireSampleClassCastExcep.class.getName()) );
fail( "incorrectly loaded class that threw class cast exception");
} catch ( LuaError le ) {
String msg = le.getMessage();
if ( msg.indexOf("not found") < 0 )
fail( "expected 'not found' message but got "+msg );
}
}
}

View File

@@ -1,16 +1,21 @@
package org.luaj.vm;
package org.luaj.vm2;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.luaj.vm.LString;
import junit.framework.TestCase;
public class LStringTest extends TestCase {
import org.luaj.vm2.lib.JsePlatform;
public class StringTest extends TestCase {
protected void setUp() throws Exception {
JsePlatform.standardGlobals();
}
public void testToInputStream() throws IOException {
LString str = new LString("Hello");
LuaString str = LuaString.valueOf("Hello");
InputStream is = str.toInputStream();
@@ -31,7 +36,7 @@ public class LStringTest extends TestCase {
is.reset();
assertEquals( 'e', is.read() );
LString substr = str.substring( 1, 4 );
LuaString substr = str.substring( 1, 4 );
assertEquals( 3, substr.length() );
is.close();
@@ -66,14 +71,14 @@ public class LStringTest extends TestCase {
for ( int i=4; i<0xffff; i+=4 ) {
char[] c = { (char) (i+0), (char) (i+1), (char) (i+2), (char) (i+3) };
String before = new String(c)+" "+i+"-"+(i+4);
LString ls = new LString(before);
String after = ls.toJavaString();
LuaString ls = LuaString.valueOf(before);
String after = ls.tojstring();
assertEquals( userFriendly( before ), userFriendly( after ) );
}
char[] c = { (char) (1), (char) (2), (char) (3) };
String before = new String(c)+" 1-3";
LString ls = new LString(before);
String after = ls.toJavaString();
LuaString ls = LuaString.valueOf(before);
String after = ls.tojstring();
assertEquals( userFriendly( before ), userFriendly( after ) );
}
@@ -81,7 +86,7 @@ public class LStringTest extends TestCase {
public void testSpotCheckUtf8() throws UnsupportedEncodingException {
byte[] bytes = {(byte)194,(byte)160,(byte)194,(byte)161,(byte)194,(byte)162,(byte)194,(byte)163,(byte)194,(byte)164};
String expected = new String(bytes, "UTF8");
String actual = new LString(bytes).toJavaString();
String actual = LuaString.valueOf(bytes).tojstring();
char[] d = actual.toCharArray();
assertEquals(160, d[0]);
assertEquals(161, d[1]);
@@ -94,8 +99,8 @@ public class LStringTest extends TestCase {
public void testNullTerminated() {
char[] c = { 'a', 'b', 'c', '\0', 'd', 'e', 'f' };
String before = new String(c);
LString ls = new LString(before);
String after = ls.toJavaString();
LuaString ls = LuaString.valueOf(before);
String after = ls.tojstring();
assertEquals( userFriendly( "abc" ), userFriendly( after ) );
}

View File

@@ -0,0 +1,17 @@
package org.luaj.vm2.require;
import org.luaj.vm2.LuaValue;
/**
* This should fail while trying to load via "require() because it is not a LibFunction"
*
*/
public class RequireSampleClassCastExcep {
public RequireSampleClassCastExcep() {
}
public LuaValue call() {
return LuaValue.valueOf("require-sample-class-cast-excep");
}
}

View File

@@ -0,0 +1,20 @@
package org.luaj.vm2.require;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.ZeroArgFunction;
/**
* This should fail while trying to load via
* "require()" because it throws a LuaError
*
*/
public class RequireSampleLoadLuaError extends ZeroArgFunction {
public RequireSampleLoadLuaError() {
}
public LuaValue call() {
error("sample-load-lua-error");
return LuaValue.valueOf("require-sample-load-lua-error");
}
}

View File

@@ -0,0 +1,18 @@
package org.luaj.vm2.require;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.ZeroArgFunction;
/**
* This should fail while trying to load via "require()" because it throws a RuntimeException
*
*/
public class RequireSampleLoadRuntimeExcep extends ZeroArgFunction {
public RequireSampleLoadRuntimeExcep() {
}
public LuaValue call() {
throw new RuntimeException("sample-load-runtime-exception");
}
}

View File

@@ -0,0 +1,17 @@
package org.luaj.vm2.require;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.ZeroArgFunction;
/**
* This should succeed as a library that can be loaded dynamically via "require()"
*/
public class RequireSampleSuccess extends ZeroArgFunction {
public RequireSampleSuccess() {
}
public LuaValue call() {
return LuaValue.valueOf("require-sample-success");
}
}