Cleanup Tests with JUnit5 and move to different modules

This commit is contained in:
Enrico Horn
2021-07-11 23:01:01 +02:00
parent 1a6de4a227
commit 9792fcb018
64 changed files with 2355 additions and 1806 deletions

View File

@@ -14,4 +14,12 @@
<name>luaj-core</name>
<description>Core code for LuaJ</description>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -21,32 +21,29 @@
******************************************************************************/
package org.luaj.vm2;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.ByteArrayInputStream;
import junit.framework.TestCase;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.Globals.BufferedStream;
public class BufferedStreamTest extends TestCase {
public BufferedStreamTest() {}
class BufferedStreamTest {
private BufferedStream NewBufferedStream(int buflen, String contents) {
return new BufferedStream(buflen, new ByteArrayInputStream(contents.getBytes()));
}
protected void setUp() throws Exception {
super.setUp();
}
public void testReadEmptyStream() throws java.io.IOException {
@Test
void testReadEmptyStream() throws java.io.IOException {
BufferedStream bs = NewBufferedStream(4, "");
assertEquals(-1, bs.read());
assertEquals(-1, bs.read(new byte[10]));
assertEquals(-1, bs.read(new byte[10], 0, 10));
}
public void testReadByte() throws java.io.IOException {
@Test
void testReadByte() throws java.io.IOException {
BufferedStream bs = NewBufferedStream(2, "abc");
assertEquals('a', bs.read());
assertEquals('b', bs.read());
@@ -54,7 +51,8 @@ public class BufferedStreamTest extends TestCase {
assertEquals(-1, bs.read());
}
public void testReadByteArray() throws java.io.IOException {
@Test
void testReadByteArray() throws java.io.IOException {
byte[] array = new byte[3];
BufferedStream bs = NewBufferedStream(4, "abcdef");
assertEquals(3, bs.read(array));
@@ -66,7 +64,8 @@ public class BufferedStreamTest extends TestCase {
assertEquals(-1, bs.read());
}
public void testReadByteArrayOffsetLength() throws java.io.IOException {
@Test
void testReadByteArrayOffsetLength() throws java.io.IOException {
byte[] array = new byte[10];
BufferedStream bs = NewBufferedStream(8, "abcdefghijklmn");
assertEquals(4, bs.read(array, 0, 4));
@@ -78,7 +77,8 @@ public class BufferedStreamTest extends TestCase {
assertEquals(-1, bs.read());
}
public void testMarkOffsetBeginningOfStream() throws java.io.IOException {
@Test
void testMarkOffsetBeginningOfStream() throws java.io.IOException {
byte[] array = new byte[4];
BufferedStream bs = NewBufferedStream(8, "abcdefghijkl");
assertEquals(true, bs.markSupported());
@@ -95,7 +95,8 @@ public class BufferedStreamTest extends TestCase {
assertEquals(-1, bs.read());
}
public void testMarkOffsetMiddleOfStream() throws java.io.IOException {
@Test
void testMarkOffsetMiddleOfStream() throws java.io.IOException {
byte[] array = new byte[4];
BufferedStream bs = NewBufferedStream(8, "abcdefghijkl");
assertEquals(true, bs.markSupported());

View File

@@ -21,17 +21,16 @@
******************************************************************************/
package org.luaj.vm2;
import java.io.Reader;
import java.io.StringReader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import java.lang.reflect.InvocationTargetException;
import junit.framework.TestCase;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.TypeTest.MyData;
import org.luaj.vm2.compiler.LuaC;
import org.luaj.vm2.lib.ZeroArgFunction;
public class LuaOperationsTest extends TestCase {
class LuaOperationsTest {
private final int sampleint = 77;
private final long samplelong = 123400000000L;
@@ -57,6 +56,7 @@ public class LuaOperationsTest extends TestCase {
private final LuaTable table = LuaValue
.listOf(new LuaValue[] { LuaValue.valueOf("aaa"), LuaValue.valueOf("bbb") });
private final LuaValue somefunc = new ZeroArgFunction() {
@Override
public LuaValue call() { return NONE; }
};
private final LuaThread thread = new LuaThread(new Globals(), somefunc);
@@ -91,7 +91,8 @@ public class LuaOperationsTest extends TestCase {
}
}
public void testLen() {
@Test
void testLen() {
throwsLuaError("len", somenil);
throwsLuaError("len", sometrue);
throwsLuaError("len", somefalse);
@@ -111,7 +112,8 @@ public class LuaOperationsTest extends TestCase {
throwsLuaError("len", userdatacls);
}
public void testLength() {
@Test
void testLength() {
throwsLuaError("length", somenil);
throwsLuaError("length", sometrue);
throwsLuaError("length", somefalse);
@@ -130,51 +132,4 @@ public class LuaOperationsTest extends TestCase {
throwsLuaError("length", userdataobj);
throwsLuaError("length", userdatacls);
}
public Prototype createPrototype(String script, String name) {
try {
Globals globals = org.luaj.vm2.lib.jse.JsePlatform.standardGlobals();
Reader reader = new StringReader(script);
return globals.compilePrototype(reader, name);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
fail(e.toString());
return null;
}
}
public void testFunctionClosureThreadEnv() {
// set up suitable environments for execution
LuaValue aaa = LuaValue.valueOf("aaa");
LuaValue eee = LuaValue.valueOf("eee");
final Globals globals = org.luaj.vm2.lib.jse.JsePlatform.standardGlobals();
LuaTable newenv = LuaValue.tableOf(new LuaValue[] { LuaValue.valueOf("a"), LuaValue.valueOf("aaa"),
LuaValue.valueOf("b"), LuaValue.valueOf("bbb"), });
LuaTable mt = LuaValue.tableOf(new LuaValue[] { LuaValue.INDEX, globals });
newenv.setmetatable(mt);
globals.set("a", aaa);
newenv.set("a", eee);
// function tests
{
LuaFunction f = new ZeroArgFunction() {
public LuaValue call() { return globals.get("a"); }
};
assertEquals(aaa, f.call());
}
// closure tests
{
Prototype p = createPrototype("return a\n", "closuretester");
LuaClosure c = new LuaClosure(p, globals);
// Test that a clusure with a custom enviroment uses that environment.
assertEquals(aaa, c.call());
c = new LuaClosure(p, newenv);
assertEquals(newenv, c.upValues[0].getValue());
assertEquals(eee, c.call());
}
}
}

View File

@@ -21,15 +21,18 @@
******************************************************************************/
package org.luaj.vm2;
import junit.framework.TestCase;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.TypeTest.MyData;
import org.luaj.vm2.lib.StringLib;
import org.luaj.vm2.lib.ThreeArgFunction;
import org.luaj.vm2.lib.TwoArgFunction;
import org.luaj.vm2.lib.ZeroArgFunction;
public class MetatableTest extends TestCase {
class MetatableTest {
private final String samplestring = "abcdef";
private final Object sampleobject = new Object();
@@ -38,6 +41,7 @@ public class MetatableTest extends TestCase {
private final LuaValue string = LuaValue.valueOf(samplestring);
private final LuaTable table = LuaValue.tableOf();
private final LuaFunction function = new ZeroArgFunction() {
@Override
public LuaValue call() { return NONE; }
};
private final LuaThread thread = new LuaThread(new Globals(), function);
@@ -45,13 +49,14 @@ public class MetatableTest extends TestCase {
private final LuaUserdata userdata = LuaValue.userdataOf(sampleobject);
private final LuaUserdata userdatamt = LuaValue.userdataOf(sampledata, table);
@BeforeEach
protected void setUp() throws Exception {
// needed for metatable ops to work on strings
new StringLib();
}
@AfterEach
protected void tearDown() throws Exception {
super.tearDown();
LuaBoolean.s_metatable = null;
LuaFunction.s_metatable = null;
LuaNil.s_metatable = null;
@@ -60,7 +65,8 @@ public class MetatableTest extends TestCase {
LuaThread.s_metatable = null;
}
public void testGetMetatable() {
@Test
void testGetMetatable() {
assertEquals(null, LuaValue.NIL.getmetatable());
assertEquals(null, LuaValue.TRUE.getmetatable());
assertEquals(null, LuaValue.ONE.getmetatable());
@@ -73,7 +79,8 @@ public class MetatableTest extends TestCase {
assertEquals(table, userdatamt.getmetatable());
}
public void testSetMetatable() {
@Test
void testSetMetatable() {
LuaValue mt = LuaValue.tableOf();
assertEquals(null, table.getmetatable());
assertEquals(null, userdata.getmetatable());
@@ -127,7 +134,8 @@ public class MetatableTest extends TestCase {
assertEquals(mt, thread.getmetatable());
}
public void testMetatableIndex() {
@Test
void testMetatableIndex() {
assertEquals(table, table.setmetatable(null));
assertEquals(userdata, userdata.setmetatable(null));
assertEquals(userdatamt, userdatamt.setmetatable(null));
@@ -168,6 +176,7 @@ public class MetatableTest extends TestCase {
// plain metatable
mt.set(LuaValue.INDEX, new TwoArgFunction() {
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2) {
return LuaValue.valueOf(arg1.typename() + "[" + arg2.tojstring() + "]=xyz");
}
@@ -183,7 +192,8 @@ public class MetatableTest extends TestCase {
assertEquals("thread[1]=xyz", thread.get(1).tojstring());
}
public void testMetatableNewIndex() {
@Test
void testMetatableNewIndex() {
// empty metatable
LuaValue mt = LuaValue.tableOf();
assertEquals(table, table.setmetatable(mt));
@@ -218,6 +228,7 @@ public class MetatableTest extends TestCase {
// metatable with function call
mt.set(LuaValue.NEWINDEX, new ThreeArgFunction() {
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) {
fallback.rawset(arg2, LuaValue.valueOf("via-func-" + arg3));
return NONE;
@@ -266,7 +277,8 @@ public class MetatableTest extends TestCase {
LuaValue.valueOf(val2), });
}
public void testRawsetMetatableSet() {
@Test
void testRawsetMetatableSet() {
// set up tables
LuaValue m = makeTable("aa", "aaa", "bb", "bbb");
m.set(LuaValue.INDEX, m);
@@ -356,7 +368,5 @@ public class MetatableTest extends TestCase {
checkTable(s, www, zzz, qqq, ddd, xxx, yyy, ttt, www, nil, qqq, ddd, xxx, nil, nil);
checkTable(t, aaa, zzz, ccc, sss, nil, yyy, ttt, nil, zzz, ccc, sss, nil, nil, nil);
checkTable(m, aaa, bbb, nil, nil, nil, yyy, ttt, aaa, bbb, nil, nil, nil, yyy, ttt);
}
}

View File

@@ -1,20 +1,21 @@
package org.luaj.vm2;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import junit.framework.TestCase;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.lib.jse.JsePlatform;
class StringTest {
public class StringTest extends TestCase {
protected void setUp() throws Exception {
JsePlatform.standardGlobals();
}
public void testToInputStream() throws IOException {
@Test
void testToInputStream() throws IOException {
LuaString str = LuaString.valueOf("Hello");
InputStream is = str.toInputStream();
@@ -66,7 +67,8 @@ public class StringTest extends TestCase {
return sb.toString();
}
public void testUtf820482051() throws UnsupportedEncodingException {
@Test
void testUtf820482051() throws UnsupportedEncodingException {
int i = 2048;
char[] c = { (char) (i+0), (char) (i+1), (char) (i+2), (char) (i+3) };
String before = new String(c) + " " + i + "-" + (i+4);
@@ -75,7 +77,8 @@ public class StringTest extends TestCase {
assertEquals(userFriendly(before), userFriendly(after));
}
public void testUtf8() {
@Test
void testUtf8() {
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);
@@ -90,7 +93,8 @@ public class StringTest extends TestCase {
assertEquals(userFriendly(before), userFriendly(after));
}
public void testSpotCheckUtf8() throws UnsupportedEncodingException {
@Test
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");
@@ -104,7 +108,8 @@ public class StringTest extends TestCase {
assertEquals(expected, actual);
}
public void testNullTerminated() {
@Test
void testNullTerminated() {
char[] c = { 'a', 'b', 'c', '\0', 'd', 'e', 'f' };
String before = new String(c);
LuaString ls = LuaString.valueOf(before);
@@ -112,7 +117,8 @@ public class StringTest extends TestCase {
assertEquals(userFriendly("abc\0def"), userFriendly(after));
}
public void testRecentStringsCacheDifferentHashcodes() {
@Test
void testRecentStringsCacheDifferentHashcodes() {
final byte[] abc = { 'a', 'b', 'c' };
final byte[] xyz = { 'x', 'y', 'z' };
final LuaString abc1 = LuaString.valueOf(abc);
@@ -125,7 +131,8 @@ public class StringTest extends TestCase {
assertSame(xyz1, xyz2);
}
public void testRecentStringsCacheHashCollisionCacheHit() {
@Test
void testRecentStringsCacheHashCollisionCacheHit() {
final byte[] abc = { 'a', 'b', 'c' };
final byte[] lyz = { 'l', 'y', 'z' }; // chosen to have hash collision with 'abc'
final LuaString abc1 = LuaString.valueOf(abc);
@@ -140,7 +147,8 @@ public class StringTest extends TestCase {
assertSame(lyz1, lyz2);
}
public void testRecentStringsCacheHashCollisionCacheMiss() {
@Test
void testRecentStringsCacheHashCollisionCacheMiss() {
final byte[] abc = { 'a', 'b', 'c' };
final byte[] lyz = { 'l', 'y', 'z' }; // chosen to have hash collision with 'abc'
final LuaString abc1 = LuaString.valueOf(abc);
@@ -155,7 +163,8 @@ public class StringTest extends TestCase {
assertNotSame(lyz1, lyz2);
}
public void testRecentStringsLongStrings() {
@Test
void testRecentStringsLongStrings() {
byte[] abc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes();
assertTrue(abc.length > LuaString.RECENT_STRINGS_MAX_LENGTH);
LuaString abc1 = LuaString.valueOf(abc);
@@ -163,7 +172,8 @@ public class StringTest extends TestCase {
assertNotSame(abc1, abc2);
}
public void testRecentStringsUsingJavaStrings() {
@Test
void testRecentStringsUsingJavaStrings() {
final String abc = "abc";
final String lyz = "lyz"; // chosen to have hash collision with 'abc'
final String xyz = "xyz";
@@ -193,7 +203,8 @@ public class StringTest extends TestCase {
assertSame(xyz3, xyz4); // because hashes do not collide
}
public void testLongSubstringGetsOldBacking() {
@Test
void testLongSubstringGetsOldBacking() {
LuaString src = LuaString.valueOf("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
LuaString sub1 = src.substring(10, 40);
assertSame(src.m_bytes, sub1.m_bytes);
@@ -201,7 +212,8 @@ public class StringTest extends TestCase {
assertEquals(sub1.m_length, 30);
}
public void testShortSubstringGetsNewBacking() {
@Test
void testShortSubstringGetsNewBacking() {
LuaString src = LuaString.valueOf("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
LuaString sub1 = src.substring(10, 20);
LuaString sub2 = src.substring(10, 20);
@@ -211,7 +223,8 @@ public class StringTest extends TestCase {
assertFalse(src.m_bytes == sub1.m_bytes);
}
public void testShortSubstringOfVeryLongStringGetsNewBacking() {
@Test
void testShortSubstringOfVeryLongStringGetsNewBacking() {
LuaString src = LuaString.valueOf("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
LuaString sub1 = src.substring(10, 50);
@@ -222,7 +235,8 @@ public class StringTest extends TestCase {
assertFalse(src.m_bytes == sub1.m_bytes);
}
public void testIndexOfByteInSubstring() {
@Test
void testIndexOfByteInSubstring() {
LuaString str = LuaString.valueOf("abcdef:ghi");
LuaString sub = str.substring(2, 10);
assertEquals(10, str.m_length);
@@ -255,7 +269,8 @@ public class StringTest extends TestCase {
assertEquals(-1, sub.indexOf((byte) 'z', 7));
}
public void testIndexOfPatternInSubstring() {
@Test
void testIndexOfPatternInSubstring() {
LuaString str = LuaString.valueOf("abcdef:ghi");
LuaString sub = str.substring(2, 10);
assertEquals(10, str.m_length);
@@ -292,7 +307,8 @@ public class StringTest extends TestCase {
assertEquals(-1, sub.indexOf(xyz, 7));
}
public void testLastIndexOfPatternInSubstring() {
@Test
void testLastIndexOfPatternInSubstring() {
LuaString str = LuaString.valueOf("abcdef:ghi");
LuaString sub = str.substring(2, 10);
assertEquals(10, str.m_length);
@@ -313,7 +329,8 @@ public class StringTest extends TestCase {
assertEquals(-1, sub.lastIndexOf(xyz));
}
public void testIndexOfAnyInSubstring() {
@Test
void testIndexOfAnyInSubstring() {
LuaString str = LuaString.valueOf("abcdef:ghi");
LuaString sub = str.substring(2, 10);
assertEquals(10, str.m_length);
@@ -348,33 +365,4 @@ public class StringTest extends TestCase {
assertEquals(1, sub.indexOfAny(CdEFGHIJ));
assertEquals(-1, sub.indexOfAny(EFGHIJKL));
}
public void testMatchShortPatterns() {
LuaValue[] args = { LuaString.valueOf("%bxy") };
LuaString _ = LuaString.valueOf("");
LuaString a = LuaString.valueOf("a");
LuaString ax = LuaString.valueOf("ax");
LuaString axb = LuaString.valueOf("axb");
LuaString axby = LuaString.valueOf("axby");
LuaString xbya = LuaString.valueOf("xbya");
LuaString bya = LuaString.valueOf("bya");
LuaString xby = LuaString.valueOf("xby");
LuaString axbya = LuaString.valueOf("axbya");
LuaValue nil = LuaValue.NIL;
assertEquals(nil, _.invokemethod("match", args));
assertEquals(nil, a.invokemethod("match", args));
assertEquals(nil, ax.invokemethod("match", args));
assertEquals(nil, axb.invokemethod("match", args));
assertEquals(xby, axby.invokemethod("match", args));
assertEquals(xby, xbya.invokemethod("match", args));
assertEquals(nil, bya.invokemethod("match", args));
assertEquals(xby, xby.invokemethod("match", args));
assertEquals(xby, axbya.invokemethod("match", args));
assertEquals(xby, axbya.substring(0, 4).invokemethod("match", args));
assertEquals(nil, axbya.substring(0, 3).invokemethod("match", args));
assertEquals(xby, axbya.substring(1, 5).invokemethod("match", args));
assertEquals(nil, axbya.substring(2, 5).invokemethod("match", args));
}
}

View File

@@ -21,17 +21,16 @@
******************************************************************************/
package org.luaj.vm2;
import junit.framework.TestCase;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.luaj.vm2.LuaString;
import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.lib.TwoArgFunction;
/**
* Tests for tables used as lists.
*/
public class TableHashTest extends TestCase {
public class TableHashTest {
protected LuaTable new_Table() {
return new LuaTable();
@@ -41,7 +40,8 @@ public class TableHashTest extends TestCase {
return new LuaTable(n, m);
}
public void testSetRemove() {
@Test
void testSetRemove() {
LuaTable t = new_Table();
assertEquals(0, t.getHashLength());
@@ -94,7 +94,8 @@ public class TableHashTest extends TestCase {
}
}
public void testIndexMetatag() {
@Test
void testIndexMetatag() {
LuaTable t = new_Table();
LuaTable mt = new_Table();
LuaTable fb = new_Table();
@@ -151,11 +152,13 @@ public class TableHashTest extends TestCase {
assertEquals("nil", t.get(456).tojstring());
}
public void testIndexFunction() {
@Test
void testIndexFunction() {
final LuaTable t = new_Table();
final LuaTable mt = new_Table();
final TwoArgFunction fb = new TwoArgFunction() {
@Override
public LuaValue call(LuaValue tbl, LuaValue key) {
assertEquals(tbl, t);
return valueOf("from mt: " + key);
@@ -205,7 +208,8 @@ public class TableHashTest extends TestCase {
assertEquals("nil", t.get(456).tojstring());
}
public void testNext() {
@Test
void testNext() {
final LuaTable t = new_Table();
assertEquals(LuaValue.NIL, t.next(LuaValue.NIL));
@@ -242,7 +246,8 @@ public class TableHashTest extends TestCase {
assertEquals(LuaValue.NIL, t.next(LuaValue.valueOf("bb")));
}
public void testLoopWithRemoval() {
@Test
void testLoopWithRemoval() {
final LuaTable t = new_Table();
t.set(LuaValue.valueOf(1), LuaValue.valueOf("1"));
@@ -277,7 +282,8 @@ public class TableHashTest extends TestCase {
assertEquals(5, numEntries);
}
public void testLoopWithRemovalAndSet() {
@Test
void testLoopWithRemovalAndSet() {
final LuaTable t = new_Table();
t.set(LuaValue.valueOf(1), LuaValue.valueOf("1"));

View File

@@ -21,12 +21,18 @@
******************************************************************************/
package org.luaj.vm2;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import junit.framework.TestCase;
import org.junit.jupiter.api.Test;
public class TableTest extends TestCase {
class TableTest {
protected LuaTable new_Table() {
return new LuaTable();
@@ -52,7 +58,8 @@ public class TableTest extends TestCase {
return l.toArray(new LuaValue[t.length()]);
}
public void testInOrderIntegerKeyInsertion() {
@Test
void testInOrderIntegerKeyInsertion() {
LuaTable t = new_Table();
for (int i = 1; i <= 32; ++i) {
@@ -72,7 +79,8 @@ public class TableTest extends TestCase {
}
public void testRekeyCount() {
@Test
void testRekeyCount() {
LuaTable t = new_Table();
// NOTE: This order of insertion is important.
@@ -92,7 +100,8 @@ public class TableTest extends TestCase {
assertTrue(t.getHashLength() <= 3);
}
public void testOutOfOrderIntegerKeyInsertion() {
@Test
void testOutOfOrderIntegerKeyInsertion() {
LuaTable t = new_Table();
for (int i = 32; i > 0; --i) {
@@ -109,7 +118,8 @@ public class TableTest extends TestCase {
assertEquals(0, t.getHashLength());
}
public void testStringAndIntegerKeys() {
@Test
void testStringAndIntegerKeys() {
LuaTable t = new_Table();
for (int i = 0; i < 10; ++i) {
@@ -143,7 +153,7 @@ public class TableTest extends TestCase {
assertEquals(String.valueOf(ik), k.strvalue().tojstring());
assertTrue(ik >= 0 && ik < 10);
final int mask = 1<<ik;
assertTrue("Key \"" + ik + "\" found more than once", (stringKeys & mask) == 0);
assertTrue((stringKeys & mask) == 0, "Key \"" + ik + "\" found more than once");
stringKeys |= mask;
} else {
fail("Unexpected type of key found");
@@ -154,7 +164,8 @@ public class TableTest extends TestCase {
assertEquals(0x03FF, stringKeys);
}
public void testBadInitialCapacity() {
@Test
void testBadInitialCapacity() {
LuaTable t = new_Table(0, 1);
t.set("test", LuaValue.valueOf("foo"));
@@ -162,7 +173,8 @@ public class TableTest extends TestCase {
assertEquals(2, keyCount(t));
}
public void testRemove0() {
@Test
void testRemove0() {
LuaTable t = new_Table(2, 0);
t.set(1, LuaValue.valueOf("foo"));
@@ -179,7 +191,8 @@ public class TableTest extends TestCase {
assertEquals(LuaValue.NIL, t.get(3));
}
public void testRemove1() {
@Test
void testRemove1() {
LuaTable t = new_Table(0, 1);
t.set("test", LuaValue.valueOf("foo"));
@@ -194,7 +207,8 @@ public class TableTest extends TestCase {
assertEquals(0, keyCount(t));
}
public void testRemove2() {
@Test
void testRemove2() {
LuaTable t = new_Table(0, 1);
t.set("test", LuaValue.valueOf("foo"));
@@ -218,7 +232,8 @@ public class TableTest extends TestCase {
assertEquals(0, keyCount(t));
}
public void testShrinkNonPowerOfTwoArray() {
@Test
void testShrinkNonPowerOfTwoArray() {
LuaTable t = new_Table(6, 2);
t.set(1, "one");
@@ -253,7 +268,8 @@ public class TableTest extends TestCase {
assertEquals("ddd", t.get("dd").tojstring());
}
public void testInOrderLuaLength() {
@Test
void testInOrderLuaLength() {
LuaTable t = new_Table();
for (int i = 1; i <= 32; ++i) {
@@ -262,7 +278,8 @@ public class TableTest extends TestCase {
}
}
public void testOutOfOrderLuaLength() {
@Test
void testOutOfOrderLuaLength() {
LuaTable t = new_Table();
for (int j = 8; j < 32; j += 8) {
@@ -273,7 +290,8 @@ public class TableTest extends TestCase {
}
}
public void testStringKeysLuaLength() {
@Test
void testStringKeysLuaLength() {
LuaTable t = new_Table();
for (int i = 1; i <= 32; ++i) {
@@ -282,7 +300,8 @@ public class TableTest extends TestCase {
}
}
public void testMixedKeysLuaLength() {
@Test
void testMixedKeysLuaLength() {
LuaTable t = new_Table();
for (int i = 1; i <= 32; ++i) {
@@ -292,20 +311,20 @@ public class TableTest extends TestCase {
}
}
private static final void compareLists(LuaTable t, Vector v) {
private static final void compareLists(LuaTable t, Vector<LuaString> v) {
int n = v.size();
assertEquals(v.size(), t.length());
for (int j = 0; j < n; j++) {
Object vj = v.elementAt(j);
Object tj = t.get(j+1).tojstring();
vj = ((LuaString) vj).tojstring();
assertEquals(vj, tj);
LuaString vj = v.elementAt(j);
String tj = t.get(j+1).tojstring();
assertEquals(vj.tojstring(), tj);
}
}
public void testInsertBeginningOfList() {
@Test
void testInsertBeginningOfList() {
LuaTable t = new_Table();
Vector v = new Vector();
Vector<LuaString> v = new Vector<>();
for (int i = 1; i <= 32; ++i) {
LuaString test = LuaValue.valueOf("Test Value! " + i);
@@ -315,9 +334,10 @@ public class TableTest extends TestCase {
}
}
public void testInsertEndOfList() {
@Test
void testInsertEndOfList() {
LuaTable t = new_Table();
Vector v = new Vector();
Vector<LuaString> v = new Vector<>();
for (int i = 1; i <= 32; ++i) {
LuaString test = LuaValue.valueOf("Test Value! " + i);
@@ -327,9 +347,10 @@ public class TableTest extends TestCase {
}
}
public void testInsertMiddleOfList() {
@Test
void testInsertMiddleOfList() {
LuaTable t = new_Table();
Vector v = new Vector();
Vector<LuaString> v = new Vector<>();
for (int i = 1; i <= 32; ++i) {
LuaString test = LuaValue.valueOf("Test Value! " + i);
@@ -340,7 +361,7 @@ public class TableTest extends TestCase {
}
}
private static final void prefillLists(LuaTable t, Vector v) {
private static final void prefillLists(LuaTable t, Vector<LuaString> v) {
for (int i = 1; i <= 32; ++i) {
LuaString test = LuaValue.valueOf("Test Value! " + i);
t.insert(0, test);
@@ -348,9 +369,10 @@ public class TableTest extends TestCase {
}
}
public void testRemoveBeginningOfList() {
@Test
void testRemoveBeginningOfList() {
LuaTable t = new_Table();
Vector v = new Vector();
Vector<LuaString> v = new Vector<>();
prefillLists(t, v);
for (int i = 1; i <= 32; ++i) {
t.remove(1);
@@ -359,9 +381,10 @@ public class TableTest extends TestCase {
}
}
public void testRemoveEndOfList() {
@Test
void testRemoveEndOfList() {
LuaTable t = new_Table();
Vector v = new Vector();
Vector<LuaString> v = new Vector<>();
prefillLists(t, v);
for (int i = 1; i <= 32; ++i) {
t.remove(0);
@@ -370,9 +393,10 @@ public class TableTest extends TestCase {
}
}
public void testRemoveMiddleOfList() {
@Test
void testRemoveMiddleOfList() {
LuaTable t = new_Table();
Vector v = new Vector();
Vector<LuaString> v = new Vector<>();
prefillLists(t, v);
for (int i = 1; i <= 32; ++i) {
int m = v.size()/2;
@@ -382,7 +406,8 @@ public class TableTest extends TestCase {
}
}
public void testRemoveWhileIterating() {
@Test
void testRemoveWhileIterating() {
LuaTable t = LuaValue.tableOf(
new LuaValue[] { LuaValue.valueOf("a"), LuaValue.valueOf("aa"), LuaValue.valueOf("b"),
LuaValue.valueOf("bb"), LuaValue.valueOf("c"), LuaValue.valueOf("cc"), LuaValue.valueOf("d"),
@@ -390,7 +415,7 @@ public class TableTest extends TestCase {
new LuaValue[] { LuaValue.valueOf("11"), LuaValue.valueOf("22"), LuaValue.valueOf("33"),
LuaValue.valueOf("44"), LuaValue.valueOf("55"), });
// Find expected order after removal.
java.util.List<String> expected = new java.util.ArrayList<String>();
List<String> expected = new ArrayList<>();
Varargs n;
int i;
for (n = t.next(LuaValue.NIL), i = 0; !n.arg1().isnil(); n = t.next(n.arg1()), ++i) {
@@ -403,7 +428,7 @@ public class TableTest extends TestCase {
t.set(n.arg1(), LuaValue.NIL);
}
// Iterate over remaining table, and form list of entries still in table.
java.util.List<String> actual = new java.util.ArrayList<String>();
List<String> actual = new ArrayList<>();
for (n = t.next(LuaValue.NIL); !n.arg1().isnil(); n = t.next(n.arg1())) {
actual.add(n.arg1() + "=" + n.arg(2));
}

View File

@@ -21,17 +21,16 @@
******************************************************************************/
package org.luaj.vm2;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.lang.reflect.InvocationTargetException;
import junit.framework.TestCase;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.lib.ZeroArgFunction;
import org.luaj.vm2.lib.jse.JsePlatform;
public class TypeTest extends TestCase {
static {
JsePlatform.debugGlobals();
}
class TypeTest {
private final int sampleint = 77;
private final long samplelong = 123400000000L;
@@ -56,6 +55,7 @@ public class TypeTest extends TestCase {
private final LuaValue stringdouble = LuaValue.valueOf(samplestringdouble);
private final LuaTable table = LuaValue.tableOf();
private final LuaFunction somefunc = new ZeroArgFunction() {
@Override
public LuaValue call() { return NONE; }
};
private final LuaThread thread = new LuaThread(new Globals(), somefunc);
@@ -70,7 +70,8 @@ public class TypeTest extends TestCase {
// ===================== type checks =======================
public void testIsBoolean() {
@Test
void testIsBoolean() {
assertEquals(false, somenil.isboolean());
assertEquals(true, sometrue.isboolean());
assertEquals(true, somefalse.isboolean());
@@ -90,7 +91,8 @@ public class TypeTest extends TestCase {
assertEquals(false, someclosure.isboolean());
}
public void testIsClosure() {
@Test
void testIsClosure() {
assertEquals(false, somenil.isclosure());
assertEquals(false, sometrue.isclosure());
assertEquals(false, somefalse.isclosure());
@@ -110,7 +112,8 @@ public class TypeTest extends TestCase {
assertEquals(true, someclosure.isclosure());
}
public void testIsFunction() {
@Test
void testIsFunction() {
assertEquals(false, somenil.isfunction());
assertEquals(false, sometrue.isfunction());
assertEquals(false, somefalse.isfunction());
@@ -130,7 +133,8 @@ public class TypeTest extends TestCase {
assertEquals(true, someclosure.isfunction());
}
public void testIsInt() {
@Test
void testIsInt() {
assertEquals(false, somenil.isint());
assertEquals(false, sometrue.isint());
assertEquals(false, somefalse.isint());
@@ -149,7 +153,8 @@ public class TypeTest extends TestCase {
assertEquals(false, someclosure.isint());
}
public void testIsIntType() {
@Test
void testIsIntType() {
assertEquals(false, somenil.isinttype());
assertEquals(false, sometrue.isinttype());
assertEquals(false, somefalse.isinttype());
@@ -169,7 +174,8 @@ public class TypeTest extends TestCase {
assertEquals(false, someclosure.isinttype());
}
public void testIsLong() {
@Test
void testIsLong() {
assertEquals(false, somenil.islong());
assertEquals(false, sometrue.islong());
assertEquals(false, somefalse.islong());
@@ -188,7 +194,8 @@ public class TypeTest extends TestCase {
assertEquals(false, someclosure.islong());
}
public void testIsNil() {
@Test
void testIsNil() {
assertEquals(true, somenil.isnil());
assertEquals(false, sometrue.isnil());
assertEquals(false, somefalse.isnil());
@@ -208,7 +215,8 @@ public class TypeTest extends TestCase {
assertEquals(false, someclosure.isnil());
}
public void testIsNumber() {
@Test
void testIsNumber() {
assertEquals(false, somenil.isnumber());
assertEquals(false, sometrue.isnumber());
assertEquals(false, somefalse.isnumber());
@@ -228,7 +236,8 @@ public class TypeTest extends TestCase {
assertEquals(false, someclosure.isnumber());
}
public void testIsString() {
@Test
void testIsString() {
assertEquals(false, somenil.isstring());
assertEquals(false, sometrue.isstring());
assertEquals(false, somefalse.isstring());
@@ -247,7 +256,8 @@ public class TypeTest extends TestCase {
assertEquals(false, someclosure.isstring());
}
public void testIsThread() {
@Test
void testIsThread() {
assertEquals(false, somenil.isthread());
assertEquals(false, sometrue.isthread());
assertEquals(false, somefalse.isthread());
@@ -265,7 +275,8 @@ public class TypeTest extends TestCase {
assertEquals(false, someclosure.isthread());
}
public void testIsTable() {
@Test
void testIsTable() {
assertEquals(false, somenil.istable());
assertEquals(false, sometrue.istable());
assertEquals(false, somefalse.istable());
@@ -283,7 +294,8 @@ public class TypeTest extends TestCase {
assertEquals(false, someclosure.istable());
}
public void testIsUserdata() {
@Test
void testIsUserdata() {
assertEquals(false, somenil.isuserdata());
assertEquals(false, sometrue.isuserdata());
assertEquals(false, somefalse.isuserdata());
@@ -301,7 +313,8 @@ public class TypeTest extends TestCase {
assertEquals(false, someclosure.isuserdata());
}
public void testIsUserdataObject() {
@Test
void testIsUserdataObject() {
assertEquals(false, somenil.isuserdata(Object.class));
assertEquals(false, sometrue.isuserdata(Object.class));
assertEquals(false, somefalse.isuserdata(Object.class));
@@ -318,7 +331,8 @@ public class TypeTest extends TestCase {
assertEquals(false, someclosure.isuserdata(Object.class));
}
public void testIsUserdataMyData() {
@Test
void testIsUserdataMyData() {
assertEquals(false, somenil.isuserdata(MyData.class));
assertEquals(false, sometrue.isuserdata(MyData.class));
assertEquals(false, somefalse.isuserdata(MyData.class));
@@ -337,7 +351,8 @@ public class TypeTest extends TestCase {
// ===================== Coerce to Java =======================
public void testToBoolean() {
@Test
void testToBoolean() {
assertEquals(false, somenil.toboolean());
assertEquals(true, sometrue.toboolean());
assertEquals(false, somefalse.toboolean());
@@ -357,7 +372,8 @@ public class TypeTest extends TestCase {
assertEquals(true, someclosure.toboolean());
}
public void testToByte() {
@Test
void testToByte() {
assertEquals((byte) 0, somenil.tobyte());
assertEquals((byte) 0, somefalse.tobyte());
assertEquals((byte) 0, sometrue.tobyte());
@@ -377,7 +393,8 @@ public class TypeTest extends TestCase {
assertEquals((byte) 0, someclosure.tobyte());
}
public void testToChar() {
@Test
void testToChar() {
assertEquals((char) 0, somenil.tochar());
assertEquals((char) 0, somefalse.tochar());
assertEquals((char) 0, sometrue.tochar());
@@ -397,18 +414,19 @@ public class TypeTest extends TestCase {
assertEquals((char) 0, someclosure.tochar());
}
public void testToDouble() {
@Test
void testToDouble() {
assertEquals(0., somenil.todouble());
assertEquals(0., somefalse.todouble());
assertEquals(0., sometrue.todouble());
assertEquals(0., zero.todouble());
assertEquals((double) sampleint, intint.todouble());
assertEquals((double) samplelong, longdouble.todouble());
assertEquals((double) sampledouble, doubledouble.todouble());
assertEquals((double) 0, stringstring.todouble());
assertEquals((double) sampleint, stringint.todouble());
assertEquals((double) samplelong, stringlong.todouble());
assertEquals((double) sampledouble, stringdouble.todouble());
assertEquals(sampleint, intint.todouble());
assertEquals(samplelong, longdouble.todouble());
assertEquals(sampledouble, doubledouble.todouble());
assertEquals(0, stringstring.todouble());
assertEquals(sampleint, stringint.todouble());
assertEquals(samplelong, stringlong.todouble());
assertEquals(sampledouble, stringdouble.todouble());
assertEquals(0., thread.todouble());
assertEquals(0., table.todouble());
assertEquals(0., userdataobj.todouble());
@@ -417,17 +435,18 @@ public class TypeTest extends TestCase {
assertEquals(0., someclosure.todouble());
}
public void testToFloat() {
@Test
void testToFloat() {
assertEquals(0.f, somenil.tofloat());
assertEquals(0.f, somefalse.tofloat());
assertEquals(0.f, sometrue.tofloat());
assertEquals(0.f, zero.tofloat());
assertEquals((float) sampleint, intint.tofloat());
assertEquals((float) samplelong, longdouble.tofloat());
assertEquals(sampleint, intint.tofloat());
assertEquals(samplelong, longdouble.tofloat());
assertEquals((float) sampledouble, doubledouble.tofloat());
assertEquals((float) 0, stringstring.tofloat());
assertEquals((float) sampleint, stringint.tofloat());
assertEquals((float) samplelong, stringlong.tofloat());
assertEquals(0, stringstring.tofloat());
assertEquals(sampleint, stringint.tofloat());
assertEquals(samplelong, stringlong.tofloat());
assertEquals((float) sampledouble, stringdouble.tofloat());
assertEquals(0.f, thread.tofloat());
assertEquals(0.f, table.tofloat());
@@ -437,16 +456,17 @@ public class TypeTest extends TestCase {
assertEquals(0.f, someclosure.tofloat());
}
public void testToInt() {
@Test
void testToInt() {
assertEquals(0, somenil.toint());
assertEquals(0, somefalse.toint());
assertEquals(0, sometrue.toint());
assertEquals(0, zero.toint());
assertEquals((int) sampleint, intint.toint());
assertEquals(sampleint, intint.toint());
assertEquals((int) samplelong, longdouble.toint());
assertEquals((int) sampledouble, doubledouble.toint());
assertEquals((int) 0, stringstring.toint());
assertEquals((int) sampleint, stringint.toint());
assertEquals(0, stringstring.toint());
assertEquals(sampleint, stringint.toint());
assertEquals((int) samplelong, stringlong.toint());
assertEquals((int) sampledouble, stringdouble.toint());
assertEquals(0, thread.toint());
@@ -457,17 +477,18 @@ public class TypeTest extends TestCase {
assertEquals(0, someclosure.toint());
}
public void testToLong() {
@Test
void testToLong() {
assertEquals(0L, somenil.tolong());
assertEquals(0L, somefalse.tolong());
assertEquals(0L, sometrue.tolong());
assertEquals(0L, zero.tolong());
assertEquals((long) sampleint, intint.tolong());
assertEquals((long) samplelong, longdouble.tolong());
assertEquals(sampleint, intint.tolong());
assertEquals(samplelong, longdouble.tolong());
assertEquals((long) sampledouble, doubledouble.tolong());
assertEquals((long) 0, stringstring.tolong());
assertEquals((long) sampleint, stringint.tolong());
assertEquals((long) samplelong, stringlong.tolong());
assertEquals(0, stringstring.tolong());
assertEquals(sampleint, stringint.tolong());
assertEquals(samplelong, stringlong.tolong());
assertEquals((long) sampledouble, stringdouble.tolong());
assertEquals(0L, thread.tolong());
assertEquals(0L, table.tolong());
@@ -477,7 +498,8 @@ public class TypeTest extends TestCase {
assertEquals(0L, someclosure.tolong());
}
public void testToShort() {
@Test
void testToShort() {
assertEquals((short) 0, somenil.toshort());
assertEquals((short) 0, somefalse.toshort());
assertEquals((short) 0, sometrue.toshort());
@@ -497,7 +519,8 @@ public class TypeTest extends TestCase {
assertEquals((short) 0, someclosure.toshort());
}
public void testToString() {
@Test
void testToString() {
assertEquals("nil", somenil.tojstring());
assertEquals("false", somefalse.tojstring());
assertEquals("true", sometrue.tojstring());
@@ -517,7 +540,8 @@ public class TypeTest extends TestCase {
assertEquals("function: ", someclosure.tojstring().substring(0, 10));
}
public void testToUserdata() {
@Test
void testToUserdata() {
assertEquals(null, somenil.touserdata());
assertEquals(null, somefalse.touserdata());
assertEquals(null, sometrue.touserdata());
@@ -552,7 +576,8 @@ public class TypeTest extends TestCase {
fail("failed to throw LuaError as required");
}
public void testOptBoolean() {
@Test
void testOptBoolean() {
assertEquals(true, somenil.optboolean(true));
assertEquals(false, somenil.optboolean(false));
assertEquals(true, sometrue.optboolean(false));
@@ -573,7 +598,8 @@ public class TypeTest extends TestCase {
throwsError(userdatacls, "optboolean", boolean.class, Boolean.FALSE);
}
public void testOptClosure() {
@Test
void testOptClosure() {
assertEquals(someclosure, somenil.optclosure(someclosure));
assertEquals(null, somenil.optclosure(null));
throwsError(sometrue, "optclosure", LuaClosure.class, someclosure);
@@ -595,19 +621,20 @@ public class TypeTest extends TestCase {
throwsError(userdatacls, "optclosure", LuaClosure.class, someclosure);
}
public void testOptDouble() {
@Test
void testOptDouble() {
assertEquals(33., somenil.optdouble(33.));
throwsError(sometrue, "optdouble", double.class, 33.);
throwsError(somefalse, "optdouble", double.class, 33.);
assertEquals(0., zero.optdouble(33.));
assertEquals((double) sampleint, intint.optdouble(33.));
assertEquals((double) samplelong, longdouble.optdouble(33.));
assertEquals(sampleint, intint.optdouble(33.));
assertEquals(samplelong, longdouble.optdouble(33.));
assertEquals(sampledouble, doubledouble.optdouble(33.));
throwsError(somefunc, "optdouble", double.class, 33.);
throwsError(someclosure, "optdouble", double.class, 33.);
throwsError(stringstring, "optdouble", double.class, 33.);
assertEquals((double) sampleint, stringint.optdouble(33.));
assertEquals((double) samplelong, stringlong.optdouble(33.));
assertEquals(sampleint, stringint.optdouble(33.));
assertEquals(samplelong, stringlong.optdouble(33.));
assertEquals(sampledouble, stringdouble.optdouble(33.));
throwsError(thread, "optdouble", double.class, 33.);
throwsError(table, "optdouble", double.class, 33.);
@@ -615,7 +642,8 @@ public class TypeTest extends TestCase {
throwsError(userdatacls, "optdouble", double.class, 33.);
}
public void testOptFunction() {
@Test
void testOptFunction() {
assertEquals(somefunc, somenil.optfunction(somefunc));
assertEquals(null, somenil.optfunction(null));
throwsError(sometrue, "optfunction", LuaFunction.class, somefunc);
@@ -638,7 +666,8 @@ public class TypeTest extends TestCase {
throwsError(userdatacls, "optfunction", LuaFunction.class, somefunc);
}
public void testOptInt() {
@Test
void testOptInt() {
assertEquals(33, somenil.optint(33));
throwsError(sometrue, "optint", int.class, new Integer(33));
throwsError(somefalse, "optint", int.class, new Integer(33));
@@ -658,7 +687,8 @@ public class TypeTest extends TestCase {
throwsError(userdatacls, "optint", int.class, new Integer(33));
}
public void testOptInteger() {
@Test
void testOptInteger() {
assertEquals(LuaValue.valueOf(33), somenil.optinteger(LuaValue.valueOf(33)));
throwsError(sometrue, "optinteger", LuaInteger.class, LuaValue.valueOf(33));
throwsError(somefalse, "optinteger", LuaInteger.class, LuaValue.valueOf(33));
@@ -678,19 +708,20 @@ public class TypeTest extends TestCase {
throwsError(userdatacls, "optinteger", LuaInteger.class, LuaValue.valueOf(33));
}
public void testOptLong() {
@Test
void testOptLong() {
assertEquals(33L, somenil.optlong(33));
throwsError(sometrue, "optlong", long.class, new Long(33));
throwsError(somefalse, "optlong", long.class, new Long(33));
assertEquals(0L, zero.optlong(33));
assertEquals(sampleint, intint.optlong(33));
assertEquals((long) samplelong, longdouble.optlong(33));
assertEquals(samplelong, longdouble.optlong(33));
assertEquals((long) sampledouble, doubledouble.optlong(33));
throwsError(somefunc, "optlong", long.class, new Long(33));
throwsError(someclosure, "optlong", long.class, new Long(33));
throwsError(stringstring, "optlong", long.class, new Long(33));
assertEquals(sampleint, stringint.optlong(33));
assertEquals((long) samplelong, stringlong.optlong(33));
assertEquals(samplelong, stringlong.optlong(33));
assertEquals((long) sampledouble, stringdouble.optlong(33));
throwsError(thread, "optlong", long.class, new Long(33));
throwsError(table, "optlong", long.class, new Long(33));
@@ -698,7 +729,8 @@ public class TypeTest extends TestCase {
throwsError(userdatacls, "optlong", long.class, new Long(33));
}
public void testOptNumber() {
@Test
void testOptNumber() {
assertEquals(LuaValue.valueOf(33), somenil.optnumber(LuaValue.valueOf(33)));
throwsError(sometrue, "optnumber", LuaNumber.class, LuaValue.valueOf(33));
throwsError(somefalse, "optnumber", LuaNumber.class, LuaValue.valueOf(33));
@@ -718,7 +750,8 @@ public class TypeTest extends TestCase {
throwsError(userdatacls, "optnumber", LuaNumber.class, LuaValue.valueOf(33));
}
public void testOptTable() {
@Test
void testOptTable() {
assertEquals(table, somenil.opttable(table));
assertEquals(null, somenil.opttable(null));
throwsError(sometrue, "opttable", LuaTable.class, table);
@@ -740,7 +773,8 @@ public class TypeTest extends TestCase {
throwsError(userdatacls, "opttable", LuaTable.class, table);
}
public void testOptThread() {
@Test
void testOptThread() {
assertEquals(thread, somenil.optthread(thread));
assertEquals(null, somenil.optthread(null));
throwsError(sometrue, "optthread", LuaThread.class, thread);
@@ -762,7 +796,8 @@ public class TypeTest extends TestCase {
throwsError(userdatacls, "optthread", LuaThread.class, thread);
}
public void testOptJavaString() {
@Test
void testOptJavaString() {
assertEquals("xyz", somenil.optjstring("xyz"));
assertEquals(null, somenil.optjstring(null));
throwsError(sometrue, "optjstring", String.class, "xyz");
@@ -783,7 +818,8 @@ public class TypeTest extends TestCase {
throwsError(userdatacls, "optjstring", String.class, "xyz");
}
public void testOptLuaString() {
@Test
void testOptLuaString() {
assertEquals(LuaValue.valueOf("xyz"), somenil.optstring(LuaValue.valueOf("xyz")));
assertEquals(null, somenil.optstring(null));
throwsError(sometrue, "optstring", LuaString.class, LuaValue.valueOf("xyz"));
@@ -804,7 +840,8 @@ public class TypeTest extends TestCase {
throwsError(userdatacls, "optstring", LuaString.class, LuaValue.valueOf("xyz"));
}
public void testOptUserdata() {
@Test
void testOptUserdata() {
assertEquals(sampleobject, somenil.optuserdata(sampleobject));
assertEquals(sampledata, somenil.optuserdata(sampledata));
assertEquals(null, somenil.optuserdata(null));
@@ -840,7 +877,8 @@ public class TypeTest extends TestCase {
fail("failed to throw LuaError as required");
}
public void testOptUserdataClass() {
@Test
void testOptUserdataClass() {
assertEquals(sampledata, somenil.optuserdata(MyData.class, sampledata));
assertEquals(sampleobject, somenil.optuserdata(Object.class, sampleobject));
assertEquals(null, somenil.optuserdata(null));
@@ -872,7 +910,8 @@ public class TypeTest extends TestCase {
}
}
public void testOptValue() {
@Test
void testOptValue() {
assertEquals(zero, somenil.optvalue(zero));
assertEquals(stringstring, somenil.optvalue(stringstring));
assertEquals(sometrue, sometrue.optvalue(LuaValue.TRUE));
@@ -907,7 +946,8 @@ public class TypeTest extends TestCase {
fail("failed to throw LuaError as required");
}
public void testCheckBoolean() {
@Test
void testCheckBoolean() {
throwsErrorReq(somenil, "checkboolean");
assertEquals(true, sometrue.checkboolean());
assertEquals(false, somefalse.checkboolean());
@@ -927,7 +967,8 @@ public class TypeTest extends TestCase {
throwsErrorReq(userdatacls, "checkboolean");
}
public void testCheckClosure() {
@Test
void testCheckClosure() {
throwsErrorReq(somenil, "checkclosure");
throwsErrorReq(sometrue, "checkclosure");
throwsErrorReq(somefalse, "checkclosure");
@@ -948,19 +989,20 @@ public class TypeTest extends TestCase {
throwsErrorReq(userdatacls, "checkclosure");
}
public void testCheckDouble() {
@Test
void testCheckDouble() {
throwsErrorReq(somenil, "checkdouble");
throwsErrorReq(sometrue, "checkdouble");
throwsErrorReq(somefalse, "checkdouble");
assertEquals(0., zero.checkdouble());
assertEquals((double) sampleint, intint.checkdouble());
assertEquals((double) samplelong, longdouble.checkdouble());
assertEquals(sampleint, intint.checkdouble());
assertEquals(samplelong, longdouble.checkdouble());
assertEquals(sampledouble, doubledouble.checkdouble());
throwsErrorReq(somefunc, "checkdouble");
throwsErrorReq(someclosure, "checkdouble");
throwsErrorReq(stringstring, "checkdouble");
assertEquals((double) sampleint, stringint.checkdouble());
assertEquals((double) samplelong, stringlong.checkdouble());
assertEquals(sampleint, stringint.checkdouble());
assertEquals(samplelong, stringlong.checkdouble());
assertEquals(sampledouble, stringdouble.checkdouble());
throwsErrorReq(thread, "checkdouble");
throwsErrorReq(table, "checkdouble");
@@ -968,7 +1010,8 @@ public class TypeTest extends TestCase {
throwsErrorReq(userdatacls, "checkdouble");
}
public void testCheckFunction() {
@Test
void testCheckFunction() {
throwsErrorReq(somenil, "checkfunction");
throwsErrorReq(sometrue, "checkfunction");
throwsErrorReq(somefalse, "checkfunction");
@@ -990,7 +1033,8 @@ public class TypeTest extends TestCase {
throwsErrorReq(userdatacls, "checkfunction");
}
public void testCheckInt() {
@Test
void testCheckInt() {
throwsErrorReq(somenil, "checkint");
throwsErrorReq(sometrue, "checkint");
throwsErrorReq(somefalse, "checkint");
@@ -1010,7 +1054,8 @@ public class TypeTest extends TestCase {
throwsErrorReq(userdatacls, "checkint");
}
public void testCheckInteger() {
@Test
void testCheckInteger() {
throwsErrorReq(somenil, "checkinteger");
throwsErrorReq(sometrue, "checkinteger");
throwsErrorReq(somefalse, "checkinteger");
@@ -1030,19 +1075,20 @@ public class TypeTest extends TestCase {
throwsErrorReq(userdatacls, "checkinteger");
}
public void testCheckLong() {
@Test
void testCheckLong() {
throwsErrorReq(somenil, "checklong");
throwsErrorReq(sometrue, "checklong");
throwsErrorReq(somefalse, "checklong");
assertEquals(0L, zero.checklong());
assertEquals(sampleint, intint.checklong());
assertEquals((long) samplelong, longdouble.checklong());
assertEquals(samplelong, longdouble.checklong());
assertEquals((long) sampledouble, doubledouble.checklong());
throwsErrorReq(somefunc, "checklong");
throwsErrorReq(someclosure, "checklong");
throwsErrorReq(stringstring, "checklong");
assertEquals(sampleint, stringint.checklong());
assertEquals((long) samplelong, stringlong.checklong());
assertEquals(samplelong, stringlong.checklong());
assertEquals((long) sampledouble, stringdouble.checklong());
throwsErrorReq(thread, "checklong");
throwsErrorReq(table, "checklong");
@@ -1050,7 +1096,8 @@ public class TypeTest extends TestCase {
throwsErrorReq(userdatacls, "checklong");
}
public void testCheckNumber() {
@Test
void testCheckNumber() {
throwsErrorReq(somenil, "checknumber");
throwsErrorReq(sometrue, "checknumber");
throwsErrorReq(somefalse, "checknumber");
@@ -1070,7 +1117,8 @@ public class TypeTest extends TestCase {
throwsErrorReq(userdatacls, "checknumber");
}
public void testCheckTable() {
@Test
void testCheckTable() {
throwsErrorReq(somenil, "checktable");
throwsErrorReq(sometrue, "checktable");
throwsErrorReq(somefalse, "checktable");
@@ -1091,7 +1139,8 @@ public class TypeTest extends TestCase {
throwsErrorReq(userdatacls, "checktable");
}
public void testCheckThread() {
@Test
void testCheckThread() {
throwsErrorReq(somenil, "checkthread");
throwsErrorReq(sometrue, "checkthread");
throwsErrorReq(somefalse, "checkthread");
@@ -1112,7 +1161,8 @@ public class TypeTest extends TestCase {
throwsErrorReq(userdatacls, "checkthread");
}
public void testCheckJavaString() {
@Test
void testCheckJavaString() {
throwsErrorReq(somenil, "checkjstring");
throwsErrorReq(sometrue, "checkjstring");
throwsErrorReq(somefalse, "checkjstring");
@@ -1132,7 +1182,8 @@ public class TypeTest extends TestCase {
throwsErrorReq(userdatacls, "checkjstring");
}
public void testCheckLuaString() {
@Test
void testCheckLuaString() {
throwsErrorReq(somenil, "checkstring");
throwsErrorReq(sometrue, "checkstring");
throwsErrorReq(somefalse, "checkstring");
@@ -1152,7 +1203,8 @@ public class TypeTest extends TestCase {
throwsErrorReq(userdatacls, "checkstring");
}
public void testCheckUserdata() {
@Test
void testCheckUserdata() {
throwsErrorReq(somenil, "checkuserdata");
throwsErrorReq(sometrue, "checkuserdata");
throwsErrorReq(somefalse, "checkuserdata");
@@ -1186,7 +1238,8 @@ public class TypeTest extends TestCase {
fail("failed to throw LuaError as required");
}
public void testCheckUserdataClass() {
@Test
void testCheckUserdataClass() {
throwsErrorReqCheckUserdataClass(somenil, Object.class);
throwsErrorReqCheckUserdataClass(somenil, MyData.class);
throwsErrorReqCheckUserdataClass(sometrue, Object.class);
@@ -1217,7 +1270,8 @@ public class TypeTest extends TestCase {
}
}
public void testCheckValue() {
@Test
void testCheckValue() {
throwsErrorReq(somenil, "checknotnil");
assertEquals(sometrue, sometrue.checknotnil());
assertEquals(somefalse, somefalse.checknotnil());

View File

@@ -21,25 +21,33 @@
******************************************************************************/
package org.luaj.vm2;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.lang.reflect.InvocationTargetException;
import junit.framework.TestCase;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.lib.TwoArgFunction;
/**
* Tests of basic unary and binary operators on main value types.
*/
public class UnaryBinaryOperatorsTest extends TestCase {
class UnaryBinaryOperatorsTest {
LuaValue dummy;
@BeforeEach
protected void setUp() throws Exception {
super.setUp();
dummy = LuaValue.ZERO;
}
public void testEqualsBool() {
@Test
void testEqualsBool() {
assertEquals(LuaValue.FALSE, LuaValue.FALSE);
assertEquals(LuaValue.TRUE, LuaValue.TRUE);
assertTrue(LuaValue.FALSE.equals(LuaValue.FALSE));
@@ -66,7 +74,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
assertFalse(LuaValue.FALSE.toboolean());
}
public void testNot() {
@Test
void testNot() {
LuaValue ia = LuaValue.valueOf(3);
LuaValue da = LuaValue.valueOf(.25);
LuaValue sa = LuaValue.valueOf("1.5");
@@ -80,7 +89,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
assertEquals(LuaValue.TRUE, bb.not());
}
public void testNeg() {
@Test
void testNeg() {
LuaValue ia = LuaValue.valueOf(3), ib = LuaValue.valueOf(-4);
LuaValue da = LuaValue.valueOf(.25), db = LuaValue.valueOf(-.5);
LuaValue sa = LuaValue.valueOf("1.5"), sb = LuaValue.valueOf("-2.0");
@@ -94,7 +104,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
assertEquals(2.0, sb.neg().todouble());
}
public void testDoublesBecomeInts() {
@Test
void testDoublesBecomeInts() {
// DoubleValue.valueOf should return int
LuaValue ia = LuaInteger.valueOf(345), da = LuaDouble.valueOf(345.0), db = LuaDouble.valueOf(345.5);
LuaValue sa = LuaValue.valueOf("3.0"), sb = LuaValue.valueOf("3"), sc = LuaValue.valueOf("-2.0"),
@@ -120,7 +131,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
}
public void testEqualsInt() {
@Test
void testEqualsInt() {
LuaValue ia = LuaInteger.valueOf(345), ib = LuaInteger.valueOf(345), ic = LuaInteger.valueOf(-345);
LuaString sa = LuaString.valueOf("345"), sb = LuaString.valueOf("345"), sc = LuaString.valueOf("-345");
@@ -141,7 +153,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
assertFalse(sa.equals(ia));
}
public void testEqualsDouble() {
@Test
void testEqualsDouble() {
LuaValue da = LuaDouble.valueOf(345.5), db = LuaDouble.valueOf(345.5), dc = LuaDouble.valueOf(-345.5);
LuaString sa = LuaString.valueOf("345.5"), sb = LuaString.valueOf("345.5"), sc = LuaString.valueOf("-345.5");
@@ -162,7 +175,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
assertFalse(sa.equals(da));
}
public void testEqInt() {
@Test
void testEqInt() {
LuaValue ia = LuaInteger.valueOf(345), ib = LuaInteger.valueOf(345), ic = LuaInteger.valueOf(-123);
LuaValue sa = LuaString.valueOf("345"), sb = LuaString.valueOf("345"), sc = LuaString.valueOf("-345");
@@ -186,7 +200,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
assertEquals(LuaValue.NIL.eq(ia), LuaValue.FALSE);
}
public void testEqDouble() {
@Test
void testEqDouble() {
LuaValue da = LuaDouble.valueOf(345.5), db = LuaDouble.valueOf(345.5), dc = LuaDouble.valueOf(-345.5);
LuaValue sa = LuaString.valueOf("345.5"), sb = LuaString.valueOf("345.5"), sc = LuaString.valueOf("-345.5");
@@ -211,18 +226,21 @@ public class UnaryBinaryOperatorsTest extends TestCase {
}
private static final TwoArgFunction RETURN_NIL = new TwoArgFunction() {
@Override
public LuaValue call(LuaValue lhs, LuaValue rhs) {
return NIL;
}
};
private static final TwoArgFunction RETURN_ONE = new TwoArgFunction() {
@Override
public LuaValue call(LuaValue lhs, LuaValue rhs) {
return ONE;
}
};
public void testEqualsMetatag() {
@Test
void testEqualsMetatag() {
LuaValue tru = LuaValue.TRUE;
LuaValue fal = LuaValue.FALSE;
LuaValue zer = LuaValue.ZERO;
@@ -359,7 +377,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
}
}
public void testAdd() {
@Test
void testAdd() {
LuaValue ia = LuaValue.valueOf(111), ib = LuaValue.valueOf(44);
LuaValue da = LuaValue.valueOf(55.25), db = LuaValue.valueOf(3.5);
LuaValue sa = LuaValue.valueOf("22.125"), sb = LuaValue.valueOf("7.25");
@@ -386,7 +405,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
assertEquals(77.375, sa.add(da).todouble());
}
public void testSub() {
@Test
void testSub() {
LuaValue ia = LuaValue.valueOf(111), ib = LuaValue.valueOf(44);
LuaValue da = LuaValue.valueOf(55.25), db = LuaValue.valueOf(3.5);
LuaValue sa = LuaValue.valueOf("22.125"), sb = LuaValue.valueOf("7.25");
@@ -405,7 +425,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
assertEquals(-33.125, sa.sub(da).todouble());
}
public void testMul() {
@Test
void testMul() {
LuaValue ia = LuaValue.valueOf(3), ib = LuaValue.valueOf(4);
LuaValue da = LuaValue.valueOf(.25), db = LuaValue.valueOf(.5);
LuaValue sa = LuaValue.valueOf("1.5"), sb = LuaValue.valueOf("2.0");
@@ -424,7 +445,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
assertEquals(.375, sa.mul(da).todouble());
}
public void testDiv() {
@Test
void testDiv() {
LuaValue ia = LuaValue.valueOf(3), ib = LuaValue.valueOf(4);
LuaValue da = LuaValue.valueOf(.25), db = LuaValue.valueOf(.5);
LuaValue sa = LuaValue.valueOf("1.5"), sb = LuaValue.valueOf("2.0");
@@ -443,7 +465,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
assertEquals(1.5/.25, sa.div(da).todouble());
}
public void testPow() {
@Test
void testPow() {
LuaValue ia = LuaValue.valueOf(3), ib = LuaValue.valueOf(4);
LuaValue da = LuaValue.valueOf(4.), db = LuaValue.valueOf(.5);
LuaValue sa = LuaValue.valueOf("1.5"), sb = LuaValue.valueOf("2.0");
@@ -466,7 +489,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
return y != 0? x-y*Math.floor(x/y): Double.NaN;
}
public void testMod() {
@Test
void testMod() {
LuaValue ia = LuaValue.valueOf(3), ib = LuaValue.valueOf(-4);
LuaValue da = LuaValue.valueOf(.25), db = LuaValue.valueOf(-.5);
LuaValue sa = LuaValue.valueOf("1.5"), sb = LuaValue.valueOf("-2.0");
@@ -485,7 +509,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
assertEquals(luaMod(1.5, .25), sa.mod(da).todouble());
}
public void testArithErrors() {
@Test
void testArithErrors() {
LuaValue ia = LuaValue.valueOf(111), ib = LuaValue.valueOf(44);
LuaValue da = LuaValue.valueOf(55.25), db = LuaValue.valueOf(3.5);
LuaValue sa = LuaValue.valueOf("22.125"), sb = LuaValue.valueOf("7.25");
@@ -516,18 +541,21 @@ public class UnaryBinaryOperatorsTest extends TestCase {
}
private static final TwoArgFunction RETURN_LHS = new TwoArgFunction() {
@Override
public LuaValue call(LuaValue lhs, LuaValue rhs) {
return lhs;
}
};
private static final TwoArgFunction RETURN_RHS = new TwoArgFunction() {
@Override
public LuaValue call(LuaValue lhs, LuaValue rhs) {
return rhs;
}
};
public void testArithMetatag() {
@Test
void testArithMetatag() {
LuaValue tru = LuaValue.TRUE;
LuaValue fal = LuaValue.FALSE;
LuaValue tbl = new LuaTable();
@@ -538,37 +566,36 @@ public class UnaryBinaryOperatorsTest extends TestCase {
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
tru.sub(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
tru.mul(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
tru.div(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
tru.pow(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
tru.mod(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
// always use left argument
LuaBoolean.s_metatable = LuaValue.tableOf(new LuaValue[] { LuaValue.ADD, RETURN_LHS, });
@@ -580,13 +607,12 @@ public class UnaryBinaryOperatorsTest extends TestCase {
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
tru.sub(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
LuaBoolean.s_metatable = LuaValue.tableOf(new LuaValue[] { LuaValue.SUB, RETURN_LHS, });
assertEquals(tru, tru.sub(fal));
@@ -597,13 +623,12 @@ public class UnaryBinaryOperatorsTest extends TestCase {
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
tru.add(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
LuaBoolean.s_metatable = LuaValue.tableOf(new LuaValue[] { LuaValue.MUL, RETURN_LHS, });
assertEquals(tru, tru.mul(fal));
@@ -614,13 +639,12 @@ public class UnaryBinaryOperatorsTest extends TestCase {
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
tru.sub(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
LuaBoolean.s_metatable = LuaValue.tableOf(new LuaValue[] { LuaValue.DIV, RETURN_LHS, });
assertEquals(tru, tru.div(fal));
@@ -631,13 +655,12 @@ public class UnaryBinaryOperatorsTest extends TestCase {
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
tru.sub(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
LuaBoolean.s_metatable = LuaValue.tableOf(new LuaValue[] { LuaValue.POW, RETURN_LHS, });
assertEquals(tru, tru.pow(fal));
@@ -648,13 +671,12 @@ public class UnaryBinaryOperatorsTest extends TestCase {
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
tru.sub(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
LuaBoolean.s_metatable = LuaValue.tableOf(new LuaValue[] { LuaValue.MOD, RETURN_LHS, });
assertEquals(tru, tru.mod(fal));
@@ -665,13 +687,12 @@ public class UnaryBinaryOperatorsTest extends TestCase {
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
tru.sub(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
// always use right argument
LuaBoolean.s_metatable = LuaValue.tableOf(new LuaValue[] { LuaValue.ADD, RETURN_RHS, });
@@ -683,13 +704,12 @@ public class UnaryBinaryOperatorsTest extends TestCase {
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
tru.sub(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
LuaBoolean.s_metatable = LuaValue.tableOf(new LuaValue[] { LuaValue.SUB, RETURN_RHS, });
assertEquals(fal, tru.sub(fal));
@@ -700,13 +720,12 @@ public class UnaryBinaryOperatorsTest extends TestCase {
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
tru.add(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
LuaBoolean.s_metatable = LuaValue.tableOf(new LuaValue[] { LuaValue.MUL, RETURN_RHS, });
assertEquals(fal, tru.mul(fal));
@@ -717,13 +736,12 @@ public class UnaryBinaryOperatorsTest extends TestCase {
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
tru.sub(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
LuaBoolean.s_metatable = LuaValue.tableOf(new LuaValue[] { LuaValue.DIV, RETURN_RHS, });
assertEquals(fal, tru.div(fal));
@@ -734,13 +752,12 @@ public class UnaryBinaryOperatorsTest extends TestCase {
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
tru.sub(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
LuaBoolean.s_metatable = LuaValue.tableOf(new LuaValue[] { LuaValue.POW, RETURN_RHS, });
assertEquals(fal, tru.pow(fal));
@@ -751,13 +768,12 @@ public class UnaryBinaryOperatorsTest extends TestCase {
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
tru.sub(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
LuaBoolean.s_metatable = LuaValue.tableOf(new LuaValue[] { LuaValue.MOD, RETURN_RHS, });
assertEquals(fal, tru.mod(fal));
@@ -768,20 +784,20 @@ public class UnaryBinaryOperatorsTest extends TestCase {
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
tru.sub(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
} finally {
LuaBoolean.s_metatable = null;
}
}
public void testArithMetatagNumberTable() {
@Test
void testArithMetatagNumberTable() {
LuaValue zero = LuaValue.ZERO;
LuaValue one = LuaValue.ONE;
LuaValue tbl = new LuaTable();
@@ -791,13 +807,13 @@ public class UnaryBinaryOperatorsTest extends TestCase {
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
zero.add(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
tbl.setmetatable(LuaValue.tableOf(new LuaValue[] { LuaValue.ADD, RETURN_ONE, }));
assertEquals(one, tbl.add(zero));
assertEquals(one, zero.add(tbl));
@@ -807,13 +823,13 @@ public class UnaryBinaryOperatorsTest extends TestCase {
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
zero.sub(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
tbl.setmetatable(LuaValue.tableOf(new LuaValue[] { LuaValue.SUB, RETURN_ONE, }));
assertEquals(one, tbl.sub(zero));
assertEquals(one, zero.sub(tbl));
@@ -823,13 +839,13 @@ public class UnaryBinaryOperatorsTest extends TestCase {
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
zero.mul(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
tbl.setmetatable(LuaValue.tableOf(new LuaValue[] { LuaValue.MUL, RETURN_ONE, }));
assertEquals(one, tbl.mul(zero));
assertEquals(one, zero.mul(tbl));
@@ -839,13 +855,13 @@ public class UnaryBinaryOperatorsTest extends TestCase {
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
zero.div(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
tbl.setmetatable(LuaValue.tableOf(new LuaValue[] { LuaValue.DIV, RETURN_ONE, }));
assertEquals(one, tbl.div(zero));
assertEquals(one, zero.div(tbl));
@@ -855,13 +871,13 @@ public class UnaryBinaryOperatorsTest extends TestCase {
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
zero.pow(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
tbl.setmetatable(LuaValue.tableOf(new LuaValue[] { LuaValue.POW, RETURN_ONE, }));
assertEquals(one, tbl.pow(zero));
assertEquals(one, zero.pow(tbl));
@@ -871,19 +887,20 @@ public class UnaryBinaryOperatorsTest extends TestCase {
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
zero.mod(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
tbl.setmetatable(LuaValue.tableOf(new LuaValue[] { LuaValue.MOD, RETURN_ONE, }));
assertEquals(one, tbl.mod(zero));
assertEquals(one, zero.mod(tbl));
}
public void testCompareStrings() {
@Test
void testCompareStrings() {
// these are lexical compare!
LuaValue sa = LuaValue.valueOf("-1.5");
LuaValue sb = LuaValue.valueOf("-2.0");
@@ -908,7 +925,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
assertEquals(LuaValue.FALSE, sd.lt(sd));
}
public void testLt() {
@Test
void testLt() {
LuaValue ia = LuaValue.valueOf(3), ib = LuaValue.valueOf(4);
LuaValue da = LuaValue.valueOf(.25), db = LuaValue.valueOf(.5);
@@ -925,7 +943,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
assertEquals(.25 < 3., da.lt_b(ia));
}
public void testLtEq() {
@Test
void testLtEq() {
LuaValue ia = LuaValue.valueOf(3), ib = LuaValue.valueOf(4);
LuaValue da = LuaValue.valueOf(.25), db = LuaValue.valueOf(.5);
@@ -942,7 +961,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
assertEquals(.25 <= 3., da.lteq_b(ia));
}
public void testGt() {
@Test
void testGt() {
LuaValue ia = LuaValue.valueOf(3), ib = LuaValue.valueOf(4);
LuaValue da = LuaValue.valueOf(.25), db = LuaValue.valueOf(.5);
@@ -959,7 +979,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
assertEquals(.25 > 3., da.gt_b(ia));
}
public void testGtEq() {
@Test
void testGtEq() {
LuaValue ia = LuaValue.valueOf(3), ib = LuaValue.valueOf(4);
LuaValue da = LuaValue.valueOf(.25), db = LuaValue.valueOf(.5);
@@ -976,7 +997,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
assertEquals(.25 >= 3., da.gteq_b(ia));
}
public void testNotEq() {
@Test
void testNotEq() {
LuaValue ia = LuaValue.valueOf(3), ib = LuaValue.valueOf(4);
LuaValue da = LuaValue.valueOf(.25), db = LuaValue.valueOf(.5);
LuaValue sa = LuaValue.valueOf("1.5"), sb = LuaValue.valueOf("2.0");
@@ -1004,7 +1026,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
assertEquals(1.5 != .25, sa.neq_b(da));
}
public void testCompareErrors() {
@Test
void testCompareErrors() {
LuaValue ia = LuaValue.valueOf(111), ib = LuaValue.valueOf(44);
LuaValue da = LuaValue.valueOf(55.25), db = LuaValue.valueOf(3.5);
LuaValue sa = LuaValue.valueOf("22.125"), sb = LuaValue.valueOf("7.25");
@@ -1034,7 +1057,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
}
}
public void testCompareMetatag() {
@Test
void testCompareMetatag() {
LuaValue tru = LuaValue.TRUE;
LuaValue fal = LuaValue.FALSE;
LuaValue tbl = new LuaTable();
@@ -1076,13 +1100,13 @@ public class UnaryBinaryOperatorsTest extends TestCase {
assertEquals(tbl2, tbl2.lteq(tbl));
assertEquals(tbl, tbl.lteq(tbl3));
assertEquals(tbl3, tbl3.lteq(tbl));
} finally {
LuaBoolean.s_metatable = null;
}
}
public void testAnd() {
@Test
void testAnd() {
LuaValue ia = LuaValue.valueOf(3), ib = LuaValue.valueOf(4);
LuaValue da = LuaValue.valueOf(.25), db = LuaValue.valueOf(.5);
LuaValue sa = LuaValue.valueOf("1.5"), sb = LuaValue.valueOf("2.0");
@@ -1108,7 +1132,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
assertSame(bb, bb.and(ia));
}
public void testOr() {
@Test
void testOr() {
LuaValue ia = LuaValue.valueOf(3), ib = LuaValue.valueOf(4);
LuaValue da = LuaValue.valueOf(.25), db = LuaValue.valueOf(.5);
LuaValue sa = LuaValue.valueOf("1.5"), sb = LuaValue.valueOf("2.0");
@@ -1134,7 +1159,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
assertSame(ia, bb.or(ia));
}
public void testLexicalComparison() {
@Test
void testLexicalComparison() {
LuaValue aaa = LuaValue.valueOf("aaa");
LuaValue baa = LuaValue.valueOf("baa");
LuaValue Aaa = LuaValue.valueOf("Aaa");
@@ -1196,7 +1222,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
assertEquals(t, aaa.gteq(aaa));
}
public void testBuffer() {
@Test
void testBuffer() {
LuaValue abc = LuaValue.valueOf("abcdefghi").substring(0, 3);
LuaValue def = LuaValue.valueOf("abcdefghi").substring(3, 6);
LuaValue ghi = LuaValue.valueOf("abcdefghi").substring(6, 9);
@@ -1261,7 +1288,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
assertEquals("ghidefabc", b.value().tojstring());
}
public void testConcat() {
@Test
void testConcat() {
LuaValue abc = LuaValue.valueOf("abcdefghi").substring(0, 3);
LuaValue def = LuaValue.valueOf("abcdefghi").substring(3, 6);
LuaValue ghi = LuaValue.valueOf("abcdefghi").substring(6, 9);
@@ -1279,7 +1307,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
assertEquals("def123", def.concat(n123).tojstring());
}
public void testConcatBuffer() {
@Test
void testConcatBuffer() {
LuaValue abc = LuaValue.valueOf("abcdefghi").substring(0, 3);
LuaValue def = LuaValue.valueOf("abcdefghi").substring(3, 6);
LuaValue ghi = LuaValue.valueOf("abcdefghi").substring(6, 9);
@@ -1301,7 +1330,8 @@ public class UnaryBinaryOperatorsTest extends TestCase {
assertEquals("abcdef123", b.value().tojstring());
}
public void testConcatMetatag() {
@Test
void testConcatMetatag() {
LuaValue def = LuaValue.valueOf("abcdefghi").substring(3, 6);
LuaValue ghi = LuaValue.valueOf("abcdefghi").substring(6, 9);
LuaValue tru = LuaValue.TRUE;
@@ -1324,37 +1354,36 @@ public class UnaryBinaryOperatorsTest extends TestCase {
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
def.concat(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
tbl.concat(def.buffer()).value();
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
def.concat(tbl.buffer()).value();
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
uda.concat(def.concat(tbl.buffer())).value();
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
ghi.concat(tbl.concat(def.buffer())).value();
fail("did not throw error");
} catch (LuaError le) {
}
;
// always use right argument
LuaBoolean.s_metatable = LuaValue.tableOf(new LuaValue[] { LuaValue.CONCAT, RETURN_RHS });
@@ -1369,44 +1398,44 @@ public class UnaryBinaryOperatorsTest extends TestCase {
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
def.concat(tbl);
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
tbl.concat(def.buffer()).value();
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
def.concat(tbl.buffer()).value();
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
uda.concat(def.concat(tbl.buffer())).value();
fail("did not throw error");
} catch (LuaError le) {
}
;
try {
uda.concat(tbl.concat(def.buffer())).value();
fail("did not throw error");
} catch (LuaError le) {
}
;
} finally {
LuaBoolean.s_metatable = null;
}
}
public void testConcatErrors() {
@Test
void testConcatErrors() {
LuaValue ia = LuaValue.valueOf(111), ib = LuaValue.valueOf(44);
LuaValue da = LuaValue.valueOf(55.25), db = LuaValue.valueOf(3.5);
LuaValue sa = LuaValue.valueOf("22.125"), sb = LuaValue.valueOf("7.25");

View File

@@ -21,12 +21,15 @@
******************************************************************************/
package org.luaj.vm2;
import junit.framework.TestCase;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.Test;
/**
* Tests of basic unary and binary operators on main value types.
*/
public class VarargsTest extends TestCase {
class VarargsTest {
static LuaValue A = LuaValue.valueOf("a");
static LuaValue B = LuaValue.valueOf("b");
@@ -57,7 +60,7 @@ public class VarargsTest extends TestCase {
static Varargs FG_alt = new Varargs.PairVarargs(F, G);
static Varargs NONE = LuaValue.NONE;
static void expectEquals(Varargs x, Varargs y) {
private void expectEquals(Varargs x, Varargs y) {
assertEquals(x.narg(), y.narg());
assertEquals(x.arg1(), y.arg1());
assertEquals(x.arg(0), y.arg(0));
@@ -68,7 +71,8 @@ public class VarargsTest extends TestCase {
assertEquals(x.arg(i), y.arg(i));
}
public void testSanity() {
@Test
void testSanity() {
expectEquals(A_G, A_G);
expectEquals(A_G_alt, A_G_alt);
expectEquals(A_G, A_G_alt);
@@ -86,7 +90,8 @@ public class VarargsTest extends TestCase {
expectEquals(NIL, NIL);
}
public void testNegativeIndices() {
@Test
void testNegativeIndices() {
expectNegSubargsError(A_G);
expectNegSubargsError(A_G_alt);
expectNegSubargsError(B_E);
@@ -106,7 +111,7 @@ public class VarargsTest extends TestCase {
expectNegSubargsError(NIL);
}
static void standardTestsA_G(Varargs a_g) {
private void standardTestsA_G(Varargs a_g) {
expectEquals(A_G, a_g);
expectEquals(A_G, a_g.subargs(1));
expectEquals(C_G, a_g.subargs(3).subargs(1));
@@ -121,7 +126,7 @@ public class VarargsTest extends TestCase {
standardTestsC_G(A_G.subargs(3));
}
static void standardTestsC_G(Varargs c_g) {
private void standardTestsC_G(Varargs c_g) {
expectEquals(C_G, c_g.subargs(1));
expectEquals(E_G, c_g.subargs(3));
expectEquals(E_G, c_g.subargs(3).subargs(1));
@@ -134,7 +139,7 @@ public class VarargsTest extends TestCase {
standardTestsE_G(c_g.subargs(3));
}
static void standardTestsE_G(Varargs e_g) {
private void standardTestsE_G(Varargs e_g) {
expectEquals(E_G, e_g.subargs(1));
expectEquals(FG, e_g.subargs(2));
expectEquals(FG, e_g.subargs(2).subargs(1));
@@ -145,7 +150,7 @@ public class VarargsTest extends TestCase {
standardTestsFG(e_g.subargs(2));
}
static void standardTestsFG(Varargs fg) {
private void standardTestsFG(Varargs fg) {
expectEquals(FG, fg.subargs(1));
expectEquals(G, fg.subargs(2));
expectEquals(G, fg.subargs(2).subargs(1));
@@ -153,12 +158,13 @@ public class VarargsTest extends TestCase {
expectEquals(NONE, fg.subargs(3).subargs(1));
}
static void standardTestsNone(Varargs none) {
private void standardTestsNone(Varargs none) {
expectEquals(NONE, none.subargs(1));
expectEquals(NONE, none.subargs(2));
}
public void testVarargsSubargs() {
@Test
void testVarargsSubargs() {
standardTestsA_G(A_G);
standardTestsA_G(A_G_alt);
standardTestsC_G(C_G);
@@ -170,7 +176,8 @@ public class VarargsTest extends TestCase {
standardTestsNone(NONE);
}
public void testVarargsMore() {
@Test
void testVarargsMore() {
Varargs a_g;
a_g = LuaValue.varargsOf(new LuaValue[] { A, }, LuaValue.varargsOf(new LuaValue[] { B, C, D, E, F, G }));
standardTestsA_G(a_g);
@@ -186,13 +193,15 @@ public class VarargsTest extends TestCase {
standardTestsA_G(a_g);
}
public void testPairVarargsMore() {
@Test
void testPairVarargsMore() {
Varargs a_g = new Varargs.PairVarargs(A, new Varargs.PairVarargs(B, new Varargs.PairVarargs(C,
new Varargs.PairVarargs(D, new Varargs.PairVarargs(E, new Varargs.PairVarargs(F, G))))));
standardTestsA_G(a_g);
}
public void testArrayPartMore() {
@Test
void testArrayPartMore() {
Varargs a_g;
a_g = new Varargs.ArrayPartVarargs(Z_H_array, 1, 1, new Varargs.ArrayPartVarargs(Z_H_array, 2, 6));
standardTestsA_G(a_g);
@@ -208,7 +217,7 @@ public class VarargsTest extends TestCase {
standardTestsA_G(a_g);
}
static void expectNegSubargsError(Varargs v) {
private void expectNegSubargsError(Varargs v) {
String expected_msg = "bad argument #1: start must be > 0";
try {
v.subargs(0);

View File

@@ -0,0 +1,262 @@
/*******************************************************************************
* 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 static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.lang.ref.WeakReference;
import org.junit.jupiter.api.Test;
class WeakTableTest {
@Test
void testWeakValuesTable() {
LuaTable t = WeakTable.make(false, true);
Object obj = new Object();
LuaTable tableValue = new LuaTable();
LuaString stringValue = LuaString.valueOf("this is a test");
LuaTable tableValue2 = new LuaTable();
t.set("table", tableValue);
t.set("userdata", LuaValue.userdataOf(obj, null));
t.set("string", stringValue);
t.set("string2", LuaValue.valueOf("another string"));
t.set(1, tableValue2);
assertTrue(t.getHashLength() >= 4, "table must have at least 4 elements");
// TODO fix assert
// assertTrue(t.getArrayLength() >= 1, "array part must have 1 element");
// check that table can be used to get elements
assertEquals(tableValue, t.get("table"));
assertEquals(stringValue, t.get("string"));
assertEquals(obj, t.get("userdata").checkuserdata());
assertEquals(tableValue2, t.get(1));
// nothing should be collected, since we have strong references here
collectGarbage();
// check that elements are still there
assertEquals(tableValue, t.get("table"));
assertEquals(stringValue, t.get("string"));
assertEquals(obj, t.get("userdata").checkuserdata());
assertEquals(tableValue2, t.get(1));
// drop our strong references
obj = null;
tableValue = null;
tableValue2 = null;
stringValue = null;
// Garbage collection should cause weak entries to be dropped.
collectGarbage();
// check that they are dropped
assertEquals(LuaValue.NIL, t.get("table"));
assertEquals(LuaValue.NIL, t.get("userdata"));
assertEquals(LuaValue.NIL, t.get(1));
assertFalse(t.get("string").isnil(), "strings should not be in weak references");
}
@Test
void testWeakKeysTable() {
LuaTable t = WeakTable.make(true, false);
LuaValue key = LuaValue.userdataOf(new MyData(111));
LuaValue val = LuaValue.userdataOf(new MyData(222));
// set up the table
t.set(key, val);
assertEquals(val, t.get(key));
System.gc();
assertEquals(val, t.get(key));
// drop key and value references, replace them with new ones
WeakReference<LuaValue> origkey = new WeakReference<>(key);
WeakReference<LuaValue> origval = new WeakReference<>(val);
key = LuaValue.userdataOf(new MyData(111));
val = LuaValue.userdataOf(new MyData(222));
// new key and value should be interchangeable (feature of this test class)
assertEquals(key, origkey.get());
assertEquals(val, origval.get());
assertEquals(val, t.get(key));
assertEquals(val, t.get(origkey.get()));
assertEquals(origval.get(), t.get(key));
// value should not be reachable after gc
collectGarbage();
assertEquals(null, origkey.get());
assertEquals(LuaValue.NIL, t.get(key));
collectGarbage();
assertEquals(null, origval.get());
}
@Test
void testNext() {
LuaTable t = WeakTable.make(true, true);
LuaValue key = LuaValue.userdataOf(new MyData(111));
LuaValue val = LuaValue.userdataOf(new MyData(222));
LuaValue key2 = LuaValue.userdataOf(new MyData(333));
LuaValue val2 = LuaValue.userdataOf(new MyData(444));
LuaValue key3 = LuaValue.userdataOf(new MyData(555));
LuaValue val3 = LuaValue.userdataOf(new MyData(666));
// set up the table
t.set(key, val);
t.set(key2, val2);
t.set(key3, val3);
// forget one of the keys
key2 = null;
val2 = null;
collectGarbage();
// table should have 2 entries
int size = 0;
for (LuaValue k = t.next(LuaValue.NIL).arg1(); !k.isnil(); k = t.next(k).arg1()) {
size++;
}
assertEquals(2, size);
}
@Test
void testWeakKeysValuesTable() {
LuaTable t = WeakTable.make(true, true);
LuaValue key = LuaValue.userdataOf(new MyData(111));
LuaValue val = LuaValue.userdataOf(new MyData(222));
LuaValue key2 = LuaValue.userdataOf(new MyData(333));
LuaValue val2 = LuaValue.userdataOf(new MyData(444));
LuaValue key3 = LuaValue.userdataOf(new MyData(555));
LuaValue val3 = LuaValue.userdataOf(new MyData(666));
// set up the table
t.set(key, val);
t.set(key2, val2);
t.set(key3, val3);
assertEquals(val, t.get(key));
assertEquals(val2, t.get(key2));
assertEquals(val3, t.get(key3));
System.gc();
assertEquals(val, t.get(key));
assertEquals(val2, t.get(key2));
assertEquals(val3, t.get(key3));
// drop key and value references, replace them with new ones
WeakReference<LuaValue> origkey = new WeakReference<>(key);
WeakReference<LuaValue> origval = new WeakReference<>(val);
WeakReference<LuaValue> origkey2 = new WeakReference<>(key2);
WeakReference<LuaValue> origval2 = new WeakReference<>(val2);
WeakReference<LuaValue> origkey3 = new WeakReference<>(key3);
WeakReference<LuaValue> origval3 = new WeakReference<>(val3);
key = LuaValue.userdataOf(new MyData(111));
val = LuaValue.userdataOf(new MyData(222));
key2 = LuaValue.userdataOf(new MyData(333));
// don't drop val2, or key3
val3 = LuaValue.userdataOf(new MyData(666));
// no values should be reachable after gc
collectGarbage();
assertEquals(null, origkey.get());
assertEquals(null, origval.get());
assertEquals(null, origkey2.get());
assertEquals(null, origval3.get());
assertEquals(LuaValue.NIL, t.get(key));
assertEquals(LuaValue.NIL, t.get(key2));
assertEquals(LuaValue.NIL, t.get(key3));
// all originals should be gone after gc, then access
val2 = null;
key3 = null;
collectGarbage();
assertEquals(null, origval2.get());
assertEquals(null, origkey3.get());
}
@Test
void testReplace() {
LuaTable t = WeakTable.make(true, true);
LuaValue key = LuaValue.userdataOf(new MyData(111));
LuaValue val = LuaValue.userdataOf(new MyData(222));
LuaValue key2 = LuaValue.userdataOf(new MyData(333));
LuaValue val2 = LuaValue.userdataOf(new MyData(444));
LuaValue key3 = LuaValue.userdataOf(new MyData(555));
LuaValue val3 = LuaValue.userdataOf(new MyData(666));
// set up the table
t.set(key, val);
t.set(key2, val2);
t.set(key3, val3);
LuaValue val4 = LuaValue.userdataOf(new MyData(777));
t.set(key2, val4);
// table should have 3 entries
int size = 0;
for (LuaValue k = t.next(LuaValue.NIL).arg1(); !k.isnil() && size < 1000; k = t.next(k).arg1()) {
size++;
}
assertEquals(3, size);
}
public static class MyData {
public final int value;
public MyData(int value) {
this.value = value;
}
@Override
public int hashCode() {
return value;
}
@Override
public boolean equals(Object o) {
return (o instanceof MyData) && ((MyData) o).value == value;
}
@Override
public String toString() {
return "mydata-" + value;
}
}
static void collectGarbage() {
Runtime rt = Runtime.getRuntime();
rt.gc();
try {
Thread.sleep(20);
rt.gc();
Thread.sleep(20);
} catch (Exception e) {
e.printStackTrace();
}
rt.gc();
}
}

View File

@@ -29,6 +29,11 @@
<artifactId>cldc-1.1-stub</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,136 @@
package org.luaj.vm2.lib.jme;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.LuaValue;
class OsLibTest {
LuaValue jme_lib;
double time;
@BeforeEach
public void setUp() {
jme_lib = JmePlatform.standardGlobals().get("os");
time = 998571302000L/1000.0;
}
void test(String format, String expected) {
String actual = jme_lib.get("date").call(LuaValue.valueOf(format), LuaValue.valueOf(time)).tojstring();
assertEquals(expected, actual);
}
@Test
void testStringDateChars() { test("foo", "foo"); }
@Test
void testStringDate_a() { test("%a", "Thu"); }
@Test
void testStringDate_A() { test("%A", "Thursday"); }
@Test
void testStringDate_b() { test("%b", "Aug"); }
@Test
void testStringDate_B() { test("%B", "August"); }
@Test
void testStringDate_c() { test("%c", "Thu Aug 23 14:55:02 2001"); }
@Test
void testStringDate_d() { test("%d", "23"); }
@Test
void testStringDate_H() { test("%H", "14"); }
@Test
void testStringDate_I() { test("%I", "02"); }
@Test
void testStringDate_j() { test("%j", "235"); }
@Test
void testStringDate_m() { test("%m", "08"); }
@Test
void testStringDate_M() { test("%M", "55"); }
@Test
void testStringDate_p() { test("%p", "PM"); }
@Test
void testStringDate_S() { test("%S", "02"); }
@Test
void testStringDate_U() { test("%U", "33"); }
@Test
void testStringDate_w() { test("%w", "4"); }
@Test
void testStringDate_W() { test("%W", "34"); }
@Test
void testStringDate_x() { test("%x", "08/23/01"); }
@Test
void testStringDate_X() { test("%X", "14:55:02"); }
@Test
void testStringDate_y() { test("%y", "01"); }
@Test
void testStringDate_Y() { test("%Y", "2001"); }
@Test
void testStringDate_Pct() { test("%%", "%"); }
static final double DAY = 24.*3600.;
@Test
void testStringDate_UW_neg4() { time -= 4*DAY; test("%c %U %W", "Sun Aug 19 14:55:02 2001 33 33"); }
@Test
void testStringDate_UW_neg3() { time -= 3*DAY; test("%c %U %W", "Mon Aug 20 14:55:02 2001 33 34"); }
@Test
void testStringDate_UW_neg2() { time -= 2*DAY; test("%c %U %W", "Tue Aug 21 14:55:02 2001 33 34"); }
@Test
void testStringDate_UW_neg1() { time -= DAY; test("%c %U %W", "Wed Aug 22 14:55:02 2001 33 34"); }
@Test
void testStringDate_UW_pos0() { time += 0; test("%c %U %W", "Thu Aug 23 14:55:02 2001 33 34"); }
@Test
void testStringDate_UW_pos1() { time += DAY; test("%c %U %W", "Fri Aug 24 14:55:02 2001 33 34"); }
@Test
void testStringDate_UW_pos2() { time += 2*DAY; test("%c %U %W", "Sat Aug 25 14:55:02 2001 33 34"); }
@Test
void testStringDate_UW_pos3() { time += 3*DAY; test("%c %U %W", "Sun Aug 26 14:55:02 2001 34 34"); }
@Test
void testStringDate_UW_pos4() { time += 4*DAY; test("%c %U %W", "Mon Aug 27 14:55:02 2001 34 35"); }
@Test
void testJseOsGetenvForEnvVariables() {
LuaValue USER = LuaValue.valueOf("USER");
LuaValue jme_user = jme_lib.get("getenv").call(USER);
assertTrue(jme_user.isnil());
System.out.println("User: " + jme_user);
}
void testJseOsGetenvForSystemProperties() {
// System.setProperty("test.key.foo", "test.value.bar");
LuaValue key = LuaValue.valueOf("test.key.foo");
LuaValue value = LuaValue.valueOf("test.value.bar");
LuaValue jme_value = jme_lib.get("getenv").call(key);
assertEquals(value, jme_value);
}
}

View File

@@ -24,6 +24,11 @@
<groupId>org.apache.bcel</groupId>
<artifactId>bcel</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

@@ -1,4 +1,7 @@
package org.luaj.vm2.compiler;
package org.luaj.jse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -9,17 +12,17 @@ import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import junit.framework.TestCase;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LoadState;
import org.luaj.vm2.LuaClosure;
import org.luaj.vm2.LuaFunction;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Prototype;
import org.luaj.vm2.compiler.DumpState;
import org.luaj.vm2.lib.jse.JsePlatform;
public class DumpLoadEndianIntTest extends TestCase {
class DumpLoadEndianIntTest {
private static final String SAVECHUNKS = "SAVECHUNKS";
private static final boolean SHOULDPASS = true;
@@ -31,27 +34,30 @@ public class DumpLoadEndianIntTest extends TestCase {
private Globals globals;
@BeforeEach
protected void setUp() throws Exception {
super.setUp();
globals = JsePlatform.standardGlobals();
DumpState.ALLOW_INTEGER_CASTING = false;
}
public void testBigDoubleCompile() {
@Test
void testBigDoubleCompile() {
doTest(false, DumpState.NUMBER_FORMAT_FLOATS_OR_DOUBLES, false, mixedscript, withdoubles, withdoubles,
SHOULDPASS);
doTest(false, DumpState.NUMBER_FORMAT_FLOATS_OR_DOUBLES, true, mixedscript, withdoubles, withdoubles,
SHOULDPASS);
}
public void testLittleDoubleCompile() {
@Test
void testLittleDoubleCompile() {
doTest(true, DumpState.NUMBER_FORMAT_FLOATS_OR_DOUBLES, false, mixedscript, withdoubles, withdoubles,
SHOULDPASS);
doTest(true, DumpState.NUMBER_FORMAT_FLOATS_OR_DOUBLES, true, mixedscript, withdoubles, withdoubles,
SHOULDPASS);
}
public void testBigIntCompile() {
@Test
void testBigIntCompile() {
DumpState.ALLOW_INTEGER_CASTING = true;
doTest(false, DumpState.NUMBER_FORMAT_INTS_ONLY, false, mixedscript, withdoubles, withints, SHOULDPASS);
doTest(false, DumpState.NUMBER_FORMAT_INTS_ONLY, true, mixedscript, withdoubles, withints, SHOULDPASS);
@@ -62,7 +68,8 @@ public class DumpLoadEndianIntTest extends TestCase {
doTest(false, DumpState.NUMBER_FORMAT_INTS_ONLY, true, intscript, withints, withints, SHOULDPASS);
}
public void testLittleIntCompile() {
@Test
void testLittleIntCompile() {
DumpState.ALLOW_INTEGER_CASTING = true;
doTest(true, DumpState.NUMBER_FORMAT_INTS_ONLY, false, mixedscript, withdoubles, withints, SHOULDPASS);
doTest(true, DumpState.NUMBER_FORMAT_INTS_ONLY, true, mixedscript, withdoubles, withints, SHOULDPASS);
@@ -73,18 +80,20 @@ public class DumpLoadEndianIntTest extends TestCase {
doTest(true, DumpState.NUMBER_FORMAT_INTS_ONLY, true, intscript, withints, withints, SHOULDPASS);
}
public void testBigNumpatchCompile() {
@Test
void testBigNumpatchCompile() {
doTest(false, DumpState.NUMBER_FORMAT_NUM_PATCH_INT32, false, mixedscript, withdoubles, withdoubles,
SHOULDPASS);
doTest(false, DumpState.NUMBER_FORMAT_NUM_PATCH_INT32, true, mixedscript, withdoubles, withdoubles, SHOULDPASS);
}
public void testLittleNumpatchCompile() {
@Test
void testLittleNumpatchCompile() {
doTest(true, DumpState.NUMBER_FORMAT_NUM_PATCH_INT32, false, mixedscript, withdoubles, withdoubles, SHOULDPASS);
doTest(true, DumpState.NUMBER_FORMAT_NUM_PATCH_INT32, true, mixedscript, withdoubles, withdoubles, SHOULDPASS);
}
public void doTest(boolean littleEndian, int numberFormat, boolean stripDebug, String script,
private void doTest(boolean littleEndian, int numberFormat, boolean stripDebug, String script,
String expectedPriorDump, String expectedPostDump, boolean shouldPass) {
try {

View File

@@ -19,14 +19,22 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
package org.luaj.vm2;
package org.luaj.jse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.Reader;
import java.io.StringReader;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaClosure;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Print;
import org.luaj.vm2.Prototype;
import org.luaj.vm2.Varargs;
import org.luaj.vm2.lib.jse.JsePlatform;
import org.luaj.vm2.luajc.LuaJC;
@@ -35,27 +43,22 @@ import org.luaj.vm2.luajc.LuaJC;
* compiling during development.
*
*/
public class FragmentsTest extends TestSuite {
public class FragmentsTest {
static final int TEST_TYPE_LUAC = 0;
static final int TEST_TYPE_LUAJC = 1;
@Nested
public static class JseFragmentsTest extends FragmentsTestCase {
public JseFragmentsTest() { super(TEST_TYPE_LUAC); }
}
@Nested
public static class LuaJCFragmentsTest extends FragmentsTestCase {
public LuaJCFragmentsTest() { super(TEST_TYPE_LUAJC); }
}
public static TestSuite suite() {
TestSuite suite = new TestSuite("Compiler Fragments Tests");
suite.addTest(new TestSuite(JseFragmentsTest.class, "JSE Fragments Tests"));
suite.addTest(new TestSuite(LuaJCFragmentsTest.class, "LuaJC Fragments Tests"));
return suite;
}
abstract protected static class FragmentsTestCase extends TestCase {
abstract protected static class FragmentsTestCase {
final int TEST_TYPE;
@@ -65,7 +68,7 @@ public class FragmentsTest extends TestSuite {
public void runFragment(Varargs expected, String script) {
try {
String name = getName();
String name = this.getClass().getName();
Globals globals = JsePlatform.debugGlobals();
Reader reader = new StringReader(script);
LuaValue chunk;
@@ -91,16 +94,19 @@ public class FragmentsTest extends TestSuite {
}
}
@Test
public void testFirstArgNilExtended() {
runFragment(LuaValue.NIL, "function f1(a) print( 'f1:', a ) return a end\n" + "b = f1()\n" + "return b");
}
@Test
public void testSimpleForloop() {
runFragment(LuaValue.valueOf(77),
"for n,p in ipairs({77}) do\n" + " print('n,p',n,p)\n" + " return p\n" + "end\n");
}
@Test
public void testForloopParamUpvalues() {
runFragment(LuaValue.varargsOf(new LuaValue[] { LuaValue.valueOf(77), LuaValue.valueOf(1) }),
"for n,p in ipairs({77}) do\n" + " print('n,p',n,p)\n" + " foo = function()\n" + " return p,n\n"
@@ -108,6 +114,7 @@ public class FragmentsTest extends TestSuite {
}
@Test
public void testArgVarargsUseBoth() {
runFragment(
LuaValue
@@ -115,24 +122,29 @@ public class FragmentsTest extends TestSuite {
"function v(arg,...)\n" + " return arg,...\n" + "end\n" + "return v('a','b','c')\n");
}
@Test
public void testArgParamUseNone() {
runFragment(LuaValue.valueOf("string"),
"function v(arg,...)\n" + " return type(arg)\n" + "end\n" + "return v('abc')\n");
}
@Test
public void testSetlistVarargs() {
runFragment(LuaValue.valueOf("abc"),
"local f = function() return 'abc' end\n" + "local g = { f() }\n" + "return g[1]\n");
}
@Test
public void testSelfOp() {
runFragment(LuaValue.valueOf("bcd"), "local s = 'abcde'\n" + "return s:sub(2,4)\n");
}
@Test
public void testSetListWithOffsetAndVarargs() {
runFragment(LuaValue.valueOf(1003), "local bar = {1000, math.sqrt(9)}\n" + "return bar[1]+bar[2]\n");
}
@Test
public void testMultiAssign() {
// arargs evaluations are all done before assignments
runFragment(
@@ -141,22 +153,26 @@ public class FragmentsTest extends TestSuite {
"a,b,c = 1,10,100\n" + "a,b,c = a+b+c, a+b+c, a+b+c\n" + "return a,b,c\n");
}
@Test
public void testUpvalues() {
runFragment(LuaValue.valueOf(999),
"local a = function(x)\n" + " return function(y)\n" + " return x + y\n" + " end\n" + "end\n"
+ "local b = a(222)\n" + "local c = b(777)\n" + "print( 'c=', c )\n" + "return c\n");
}
@Test
public void testNonAsciiStringLiterals() {
runFragment(LuaValue.valueOf("7,8,12,10,9,11,133,222"), "local a='\\a\\b\\f\\n\\t\\v\\133\\222'\n"
+ "local t={string.byte(a,1,#a)}\n" + "return table.concat(t,',')\n");
}
@Test
public void testControlCharStringLiterals() {
runFragment(LuaValue.valueOf("97,0,98,18,99,18,100,18,48,101"), "local a='a\\0b\\18c\\018d\\0180e'\n"
+ "local t={string.byte(a,1,#a)}\n" + "return table.concat(t,',')\n");
}
@Test
public void testLoopVarNames() {
runFragment(LuaValue.valueOf(" 234,1,aa 234,2,bb"),
"local w = ''\n" + "function t()\n" + " for f,var in ipairs({'aa','bb'}) do\n" + " local s = 234\n"
@@ -164,6 +180,7 @@ public class FragmentsTest extends TestSuite {
}
@Test
public void testForLoops() {
runFragment(LuaValue.valueOf("12345 357 963"),
"local s,t,u = '','',''\n" + "for m=1,5 do\n" + " s = s..m\n" + "end\n" + "for m=3,7,2 do\n"
@@ -171,12 +188,14 @@ public class FragmentsTest extends TestSuite {
+ "return s..' '..t..' '..u\n");
}
@Test
public void testLocalFunctionDeclarations() {
runFragment(LuaValue.varargsOf(LuaValue.valueOf("function"), LuaValue.valueOf("nil")),
"local function aaa()\n" + " return type(aaa)\n" + "end\n" + "local bbb = function()\n"
+ " return type(bbb)\n" + "end\n" + "return aaa(),bbb()\n");
}
@Test
public void testNilsInTableConstructor() {
runFragment(LuaValue.valueOf("1=111 2=222 3=333 "),
"local t = { 111, 222, 333, nil, nil }\n" + "local s = ''\n" + "for i,v in ipairs(t) do \n"
@@ -184,6 +203,7 @@ public class FragmentsTest extends TestSuite {
}
@Test
public void testUnreachableCode() {
runFragment(LuaValue.valueOf(66),
"local function foo(x) return x * 2 end\n" + "local function bar(x, y)\n" + " if x==y then\n"
@@ -192,51 +212,61 @@ public class FragmentsTest extends TestSuite {
}
@Test
public void testVarargsWithParameters() {
runFragment(LuaValue.valueOf(222),
"local func = function(t,...)\n" + " return (...)\n" + "end\n" + "return func(111,222,333)\n");
}
@Test
public void testNoReturnValuesPlainCall() {
runFragment(LuaValue.TRUE, "local testtable = {}\n" + "return pcall( function() testtable[1]=2 end )\n");
}
@Test
public void testVarargsInTableConstructor() {
runFragment(LuaValue.valueOf(222), "local function foo() return 111,222,333 end\n"
+ "local t = {'a','b',c='c',foo()}\n" + "return t[4]\n");
}
@Test
public void testVarargsInFirstArg() {
runFragment(LuaValue.valueOf(123), "function aaa(x) return x end\n" + "function bbb(y) return y end\n"
+ "function ccc(z) return z end\n" + "return ccc( aaa(bbb(123)), aaa(456) )\n");
}
@Test
public void testSetUpvalueTableInitializer() {
runFragment(LuaValue.valueOf("b"), "local aliases = {a='b'}\n" + "local foo = function()\n"
+ " return aliases\n" + "end\n" + "return foo().a\n");
}
@Test
public void testLoadNilUpvalue() {
runFragment(LuaValue.NIL, "tostring = function() end\n" + "local pc \n" + "local pcall = function(...)\n"
+ " pc(...)\n" + "end\n" + "return NIL\n");
}
@Test
public void testUpvalueClosure() {
runFragment(LuaValue.NIL, "print()\n" + "local function f2() end\n" + "local function f3()\n"
+ " return f3\n" + "end\n" + "return NIL\n");
}
@Test
public void testUninitializedUpvalue() {
runFragment(LuaValue.NIL, "local f\n" + "do\n" + " function g()\n" + " print(f())\n" + " end\n"
+ "end\n" + "return NIL\n");
}
@Test
public void testTestOpUpvalues() {
runFragment(LuaValue.varargsOf(LuaValue.valueOf(1), LuaValue.valueOf(2), LuaValue.valueOf(3)),
"print( nil and 'T' or 'F' )\n" + "local a,b,c = 1,2,3\n" + "function foo()\n" + " return a,b,c\n"
+ "end\n" + "return foo()\n");
}
@Test
public void testTestSimpleBinops() {
runFragment(
LuaValue.varargsOf(
@@ -244,11 +274,13 @@ public class FragmentsTest extends TestSuite {
"local a,b,c = 2,-2.5,0\n" + "return (a==c), (b==c), (a==a), (a>c), (b>0)\n");
}
@Test
public void testNumericForUpvalues() {
runFragment(LuaValue.valueOf(8), "for i = 3,4 do\n" + " i = i + 5\n" + " local a = function()\n"
+ " return i\n" + " end\n" + " return a()\n" + "end\n");
}
@Test
public void testNumericForUpvalues2() {
runFragment(LuaValue.valueOf("222 222"),
"local t = {}\n" + "local template = [[123 456]]\n" + "for i = 1,2 do\n"
@@ -256,32 +288,38 @@ public class FragmentsTest extends TestSuite {
+ "return t[2]\n");
}
@Test
public void testReturnUpvalue() {
runFragment(LuaValue.varargsOf(new LuaValue[] { LuaValue.ONE, LuaValue.valueOf(5), }), "local a = 1\n"
+ "local b\n" + "function c()\n" + " b=5\n" + " return a\n" + "end\n" + "return c(),b\n");
}
@Test
public void testUninitializedAroundBranch() {
runFragment(LuaValue.valueOf(333),
"local state\n" + "if _G then\n" + " state = 333\n" + "end\n" + "return state\n");
}
@Test
public void testLoadedNilUpvalue() {
runFragment(LuaValue.NIL, "local a = print()\n" + "local b = c and { d = e }\n" + "local f\n"
+ "local function g()\n" + " return f\n" + "end\n" + "return g()\n");
}
@Test
public void testUpvalueInFirstSlot() {
runFragment(LuaValue.valueOf("foo"), "local p = {'foo'}\n" + "bar = function()\n" + " return p \n"
+ "end\n" + "for i,key in ipairs(p) do\n" + " print()\n" + "end\n" + "return bar()[1]");
}
@Test
public void testReadOnlyAndReadWriteUpvalues() {
runFragment(LuaValue.varargsOf(new LuaValue[] { LuaValue.valueOf(333), LuaValue.valueOf(222) }),
"local a = 111\n" + "local b = 222\n" + "local c = function()\n" + " a = a + b\n"
+ " return a,b\n" + "end\n" + "return c()\n");
}
@Test
public void testNestedUpvalues() {
runFragment(
LuaValue.varargsOf(new LuaValue[] { LuaValue.valueOf(5), LuaValue.valueOf(8), LuaValue.valueOf(9) }),
@@ -290,37 +328,44 @@ public class FragmentsTest extends TestSuite {
+ "return f(), g(8,9)\n" + "\n");
}
@Test
public void testLoadBool() {
runFragment(LuaValue.NONE, "print( type(foo)=='string' )\n" + "local a,b\n" + "if print() then\n"
+ " b = function()\n" + " return a\n" + " end\n" + "end\n");
}
@Test
public void testBasicForLoop() {
runFragment(LuaValue.valueOf(2), "local data\n" + "for i = 1, 2 do\n" + " data = i\n" + "end\n"
+ "local bar = function()\n" + " return data\n" + "end\n" + "return bar()\n");
}
@Test
public void testGenericForMultipleValues() {
runFragment(LuaValue.varargsOf(LuaValue.valueOf(3), LuaValue.valueOf(2), LuaValue.valueOf(1)),
"local iter = function() return 1,2,3,4 end\n" + "local foo = function() return iter,5 end\n"
+ "for a,b,c in foo() do\n" + " return c,b,a\n" + "end\n");
}
@Test
public void testPhiUpvalue() {
runFragment(LuaValue.valueOf(6), "local a = foo or 0\n" + "local function b(c)\n"
+ " if c > a then a = c end\n" + " return a\n" + "end\n" + "b(6)\n" + "return a\n");
}
@Test
public void testAssignReferUpvalues() {
runFragment(LuaValue.valueOf(123), "local entity = 234\n" + "local function c()\n" + " return entity\n"
+ "end\n" + "entity = (a == b) and 123\n" + "if entity then\n" + " return entity\n" + "end\n");
}
@Test
public void testSimpleRepeatUntil() {
runFragment(LuaValue.valueOf(5),
"local a\n" + "local w\n" + "repeat\n" + " a = w\n" + "until not a\n" + "return 5\n");
}
@Test
public void testLoopVarUpvalues() {
runFragment(LuaValue.valueOf("b"),
"local env = {}\n" + "for a,b in pairs(_G) do\n" + " c = function()\n" + " return b\n"
@@ -328,11 +373,13 @@ public class FragmentsTest extends TestSuite {
+ " return env[k] or v\n" + "end\n");
}
@Test
public void testPhiVarUpvalue() {
runFragment(LuaValue.valueOf(2), "local a = 1\n" + "local function b()\n" + " a = a + 1\n"
+ " return function() end\n" + "end\n" + "for i in b() do\n" + " a = 3\n" + "end\n" + "return a\n");
}
@Test
public void testUpvaluesInElseClauses() {
runFragment(LuaValue.valueOf(111),
"if a then\n" + " foo(bar)\n" + "elseif _G then\n" + " local x = 111\n" + " if d then\n"
@@ -340,57 +387,69 @@ public class FragmentsTest extends TestSuite {
+ " end\n" + " return y()\n" + " end\n" + "end\n");
}
@Test
public void testUpvalueInDoBlock() {
runFragment(LuaValue.NONE,
"do\n" + " local x = 10\n" + " function g()\n" + " return x\n" + " end\n" + "end\n" + "g()\n");
}
@Test
public void testNullError() {
runFragment(LuaValue.varargsOf(LuaValue.FALSE, LuaValue.NIL), "return pcall(error)\n");
}
@Test
public void testFindWithOffset() {
runFragment(LuaValue.varargsOf(LuaValue.valueOf(8), LuaValue.valueOf(5)), "string = \"abcdef:ghi\"\n"
+ "substring = string:sub(3)\n" + "idx = substring:find(\":\")\n" + "return #substring, idx\n");
}
@Test
public void testErrorArgIsString() {
runFragment(LuaValue.varargsOf(LuaValue.valueOf("string"), LuaValue.valueOf("c")),
"a,b = pcall(error, 'c'); return type(b), b\n");
}
@Test
public void testErrorArgIsNil() {
runFragment(LuaValue.varargsOf(LuaValue.valueOf("nil"), LuaValue.NIL),
"a,b = pcall(error); return type(b), b\n");
}
@Test
public void testErrorArgIsTable() {
runFragment(LuaValue.varargsOf(LuaValue.valueOf("table"), LuaValue.valueOf("d")),
"a,b = pcall(error, {c='d'}); return type(b), b.c\n");
}
@Test
public void testErrorArgIsNumber() {
runFragment(LuaValue.varargsOf(LuaValue.valueOf("string"), LuaValue.valueOf("1")),
"a,b = pcall(error, 1); return type(b), b\n");
}
@Test
public void testErrorArgIsBool() {
runFragment(LuaValue.varargsOf(LuaValue.valueOf("boolean"), LuaValue.TRUE),
"a,b = pcall(error, true); return type(b), b\n");
}
@Test
public void testBalancedMatchOnEmptyString() {
runFragment(LuaValue.NIL, "return (\"\"):match(\"%b''\")\n");
}
@Test
public void testReturnValueForTableRemove() {
runFragment(LuaValue.NONE, "return table.remove({ })");
}
@Test
public void testTypeOfTableRemoveReturnValue() {
runFragment(LuaValue.valueOf("nil"), "local k = table.remove({ }) return type(k)");
}
@Test
public void testVarargBugReport() {
runFragment(
LuaValue.varargsOf(new LuaValue[] { LuaValue.valueOf(1), LuaValue.valueOf(2), LuaValue.valueOf(3) }),

View File

@@ -19,26 +19,31 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
package org.luaj.vm2;
package org.luaj.jse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.InputStream;
import java.io.Reader;
import junit.framework.TestCase;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaString;
import org.luaj.vm2.lib.jse.JsePlatform;
import org.luaj.vm2.server.Launcher;
import org.luaj.vm2.server.LuajClassLoader;
// Tests using class loading orders that have caused problems for some use cases.
public class LoadOrderTest extends TestCase {
class LoadOrderTest {
public void testLoadGlobalsFirst() {
@Test
void testLoadGlobalsFirst() {
Globals g = JsePlatform.standardGlobals();
assertNotNull(g);
}
public void testLoadStringFirst() {
@Test
void testLoadStringFirst() {
LuaString BAR = LuaString.valueOf("bar");
assertNotNull(BAR);
}
@@ -47,20 +52,24 @@ public class LoadOrderTest extends TestCase {
// Static initializer that causes LuaString->LuaValue->LuaString
private static final LuaString FOO = LuaString.valueOf("foo");
@Override
public Object[] launch(String script, Object[] arg) {
return new Object[] { FOO };
}
@Override
public Object[] launch(InputStream script, Object[] arg) {
return null;
}
@Override
public Object[] launch(Reader script, Object[] arg) {
return null;
}
}
public void testClassLoadsStringFirst() throws Exception {
@Test
void testClassLoadsStringFirst() throws Exception {
Launcher launcher = LuajClassLoader.NewLauncher(TestLauncherLoadStringFirst.class);
Object[] results = launcher.launch("foo", null);
assertNotNull(results);

View File

@@ -0,0 +1,90 @@
/*******************************************************************************
* 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.jse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.Reader;
import java.io.StringReader;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaClosure;
import org.luaj.vm2.LuaFunction;
import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Prototype;
import org.luaj.vm2.lib.ZeroArgFunction;
import org.luaj.vm2.lib.jse.JsePlatform;
class LuaPrototypeTest {
private Prototype createPrototype(String script, String name) {
try {
Globals globals = JsePlatform.standardGlobals();
Reader reader = new StringReader(script);
return globals.compilePrototype(reader, name);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
fail(e.toString());
return null;
}
}
@Test
void testFunctionClosureThreadEnv() {
// set up suitable environments for execution
LuaValue aaa = LuaValue.valueOf("aaa");
LuaValue eee = LuaValue.valueOf("eee");
final Globals globals = JsePlatform.standardGlobals();
LuaTable newenv = LuaValue.tableOf(new LuaValue[] { LuaValue.valueOf("a"), LuaValue.valueOf("aaa"),
LuaValue.valueOf("b"), LuaValue.valueOf("bbb"), });
LuaTable mt = LuaValue.tableOf(new LuaValue[] { LuaValue.INDEX, globals });
newenv.setmetatable(mt);
globals.set("a", aaa);
newenv.set("a", eee);
// function tests
{
LuaFunction f = new ZeroArgFunction() {
@Override
public LuaValue call() { return globals.get("a"); }
};
assertEquals(aaa, f.call());
}
// closure tests
{
Prototype p = createPrototype("return a\n", "closuretester");
LuaClosure c = new LuaClosure(p, globals);
// Test that a clusure with a custom enviroment uses that environment.
assertEquals(aaa, c.call());
c = new LuaClosure(p, newenv);
assertEquals(newenv, c.upValues[0].getValue());
assertEquals(eee, c.call());
}
}
}

View File

@@ -19,48 +19,65 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
package org.luaj.vm2;
package org.luaj.jse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.lang.ref.WeakReference;
import junit.framework.TestCase;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaThread;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;
import org.luaj.vm2.lib.OneArgFunction;
import org.luaj.vm2.lib.jse.JsePlatform;
public class OrphanedThreadTest extends TestCase {
class OrphanedThreadTest {
Globals globals;
LuaThread luathread;
WeakReference luathr_ref;
LuaValue function;
WeakReference func_ref;
LuaThread luathread;
LuaValue function;
WeakReference<LuaThread> luathr_ref;
WeakReference<LuaValue> func_ref;
@BeforeEach
protected void setUp() throws Exception {
LuaThread.thread_orphan_check_interval = 5;
globals = JsePlatform.standardGlobals();
}
@AfterEach
protected void tearDown() {
LuaThread.thread_orphan_check_interval = 30000;
}
public void testCollectOrphanedNormalThread() throws Exception {
@Test
void testCollectOrphanedNormalThread() throws Exception {
function = new NormalFunction(globals);
doTest(LuaValue.TRUE, LuaValue.ZERO);
}
public void testCollectOrphanedEarlyCompletionThread() throws Exception {
@Test
void testCollectOrphanedEarlyCompletionThread() throws Exception {
function = new EarlyCompletionFunction(globals);
doTest(LuaValue.TRUE, LuaValue.ZERO);
}
public void testCollectOrphanedAbnormalThread() throws Exception {
@Test
void testCollectOrphanedAbnormalThread() throws Exception {
function = new AbnormalFunction(globals);
doTest(LuaValue.FALSE, LuaValue.valueOf("abnormal condition"));
}
public void testCollectOrphanedClosureThread() throws Exception {
@Test
void testCollectOrphanedClosureThread() throws Exception {
String script = "print('in closure, arg is '..(...))\n" + "arg = coroutine.yield(1)\n"
+ "print('in closure.2, arg is '..arg)\n" + "arg = coroutine.yield(0)\n"
+ "print('leakage in closure.3, arg is '..arg)\n" + "return 'done'\n";
@@ -68,7 +85,8 @@ public class OrphanedThreadTest extends TestCase {
doTest(LuaValue.TRUE, LuaValue.ZERO);
}
public void testCollectOrphanedPcallClosureThread() throws Exception {
@Test
void testCollectOrphanedPcallClosureThread() throws Exception {
String script = "f = function(x)\n" + " print('in pcall-closure, arg is '..(x))\n"
+ " arg = coroutine.yield(1)\n" + " print('in pcall-closure.2, arg is '..arg)\n"
+ " arg = coroutine.yield(0)\n" + " print('leakage in pcall-closure.3, arg is '..arg)\n"
@@ -77,7 +95,8 @@ public class OrphanedThreadTest extends TestCase {
doTest(LuaValue.TRUE, LuaValue.ZERO);
}
public void testCollectOrphanedLoadCloasureThread() throws Exception {
@Test
void testCollectOrphanedLoadCloasureThread() throws Exception {
String script = "t = { \"print \", \"'hello, \", \"world'\", }\n" + "i = 0\n" + "arg = ...\n"
+ "f = function()\n" + " i = i + 1\n" + " print('in load-closure, arg is', arg, 'next is', t[i])\n"
+ " arg = coroutine.yield(1)\n" + " return t[i]\n" + "end\n" + "load(f)()\n";
@@ -87,8 +106,8 @@ public class OrphanedThreadTest extends TestCase {
private void doTest(LuaValue status2, LuaValue value2) throws Exception {
luathread = new LuaThread(globals, function);
luathr_ref = new WeakReference(luathread);
func_ref = new WeakReference(function);
luathr_ref = new WeakReference<>(luathread);
func_ref = new WeakReference<>(function);
assertNotNull(luathr_ref.get());
// resume two times
@@ -121,6 +140,7 @@ public class OrphanedThreadTest extends TestCase {
this.globals = globals;
}
@Override
public LuaValue call(LuaValue arg) {
System.out.println("in normal.1, arg is " + arg);
arg = globals.yield(ONE).arg1();
@@ -138,6 +158,7 @@ public class OrphanedThreadTest extends TestCase {
this.globals = globals;
}
@Override
public LuaValue call(LuaValue arg) {
System.out.println("in early.1, arg is " + arg);
arg = globals.yield(ONE).arg1();
@@ -153,6 +174,7 @@ public class OrphanedThreadTest extends TestCase {
this.globals = globals;
}
@Override
public LuaValue call(LuaValue arg) {
System.out.println("in abnormal.1, arg is " + arg);
arg = globals.yield(ONE).arg1();

View File

@@ -1,35 +1,46 @@
package org.luaj.vm2;
package org.luaj.jse;
import junit.framework.TestCase;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.luaj.jse.require.RequireSampleClassCastExcep;
import org.luaj.jse.require.RequireSampleLoadLuaError;
import org.luaj.jse.require.RequireSampleLoadRuntimeExcep;
import org.luaj.jse.require.RequireSampleSuccess;
import org.luaj.vm2.LuaError;
import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.jse.JsePlatform;
import org.luaj.vm2.require.RequireSampleClassCastExcep;
import org.luaj.vm2.require.RequireSampleLoadLuaError;
import org.luaj.vm2.require.RequireSampleLoadRuntimeExcep;
public class RequireClassTest extends TestCase {
class RequireClassTest {
private LuaTable globals;
private LuaValue require;
@BeforeEach
public void setUp() {
globals = JsePlatform.standardGlobals();
require = globals.get("require");
}
public void testLoadClass() {
LuaValue result = globals.load(new org.luaj.vm2.require.RequireSampleSuccess());
@Test
void testLoadClass() {
LuaValue result = globals.load(new RequireSampleSuccess());
assertEquals("require-sample-success-", result.tojstring());
}
public void testRequireClassSuccess() {
LuaValue result = require.call(LuaValue.valueOf("org.luaj.vm2.require.RequireSampleSuccess"));
assertEquals("require-sample-success-org.luaj.vm2.require.RequireSampleSuccess", result.tojstring());
result = require.call(LuaValue.valueOf("org.luaj.vm2.require.RequireSampleSuccess"));
assertEquals("require-sample-success-org.luaj.vm2.require.RequireSampleSuccess", result.tojstring());
@Test
void testRequireClassSuccess() {
LuaValue result = require.call(LuaValue.valueOf(RequireSampleSuccess.class.getName()));
assertEquals("require-sample-success-" + RequireSampleSuccess.class.getName(), result.tojstring());
result = require.call(LuaValue.valueOf(RequireSampleSuccess.class.getName()));
assertEquals("require-sample-success-" + RequireSampleSuccess.class.getName(), result.tojstring());
}
public void testRequireClassLoadLuaError() {
@Test
void testRequireClassLoadLuaError() {
try {
LuaValue result = require.call(LuaValue.valueOf(RequireSampleLoadLuaError.class.getName()));
fail("incorrectly loaded class that threw lua error");
@@ -45,7 +56,8 @@ public class RequireClassTest extends TestCase {
}
}
public void testRequireClassLoadRuntimeException() {
@Test
void testRequireClassLoadRuntimeException() {
try {
LuaValue result = require.call(LuaValue.valueOf(RequireSampleLoadRuntimeExcep.class.getName()));
fail("incorrectly loaded class that threw runtime exception");
@@ -62,7 +74,8 @@ public class RequireClassTest extends TestCase {
}
}
public void testRequireClassClassCastException() {
@Test
void testRequireClassClassCastException() {
try {
LuaValue result = require.call(LuaValue.valueOf(RequireSampleClassCastExcep.class.getName()));
fail("incorrectly loaded class that threw class cast exception");

View File

@@ -1,19 +1,23 @@
package org.luaj.vm2.compiler;
package org.luaj.jse;
import junit.framework.TestCase;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaDouble;
import org.luaj.vm2.LuaInteger;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.jse.JsePlatform;
public class SimpleTests extends TestCase {
class SimpleLuaCallsTest {
private Globals globals;
@BeforeEach
protected void setUp() throws Exception {
super.setUp();
globals = JsePlatform.standardGlobals();
}
@@ -26,38 +30,45 @@ public class SimpleTests extends TestCase {
}
}
public void testTrivial() {
@Test
void testTrivial() {
String s = "print( 2 )\n";
doTest(s);
}
public void testAlmostTrivial() {
@Test
void testAlmostTrivial() {
String s = "print( 2 )\n" + "print( 3 )\n";
doTest(s);
}
public void testSimple() {
@Test
void testSimple() {
String s = "print( 'hello, world' )\n" + "for i = 2,4 do\n" + " print( 'i', i )\n" + "end\n";
doTest(s);
}
public void testBreak() {
@Test
void testBreak() {
String s = "a=1\n" + "while true do\n" + " if a>10 then\n" + " break\n" + " end\n" + " a=a+1\n"
+ " print( a )\n" + "end\n";
doTest(s);
}
public void testShebang() {
@Test
void testShebang() {
String s = "#!../lua\n" + "print( 2 )\n";
doTest(s);
}
public void testInlineTable() {
@Test
void testInlineTable() {
String s = "A = {g=10}\n" + "print( A )\n";
doTest(s);
}
public void testEqualsAnd() {
@Test
void testEqualsAnd() {
String s = "print( 1 == b and b )\n";
doTest(s);
}
@@ -65,7 +76,8 @@ public class SimpleTests extends TestCase {
private static final int[] samehash = { 0, 1, -1, 2, -2, 4, 8, 16, 32, Integer.MAX_VALUE, Integer.MIN_VALUE };
private static final double[] diffhash = { .5, 1, 1.5, 1, .5, 1.5, 1.25, 2.5 };
public void testDoubleHashCode() {
@Test
void testDoubleHashCode() {
for (int i = 0; i < samehash.length; i++) {
LuaValue j = LuaInteger.valueOf(samehash[i]);
LuaValue d = LuaDouble.valueOf(samehash[i]);
@@ -78,7 +90,7 @@ public class SimpleTests extends TestCase {
LuaValue d = LuaValue.valueOf(diffhash[i+1]);
int hc = c.hashCode();
int hd = d.hashCode();
assertTrue("hash codes are same: " + hc, hc != hd);
assertTrue(hc != hd, "hash codes are same: " + hc);
}
}
}

View File

@@ -0,0 +1,47 @@
package org.luaj.jse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.LuaString;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.jse.JsePlatform;
class StringMatchingTest {
@BeforeEach
protected void setUp() throws Exception {
JsePlatform.standardGlobals();
}
@Test
void testMatchShortPatterns() {
LuaValue[] args = { LuaString.valueOf("%bxy") };
LuaString empty = LuaString.valueOf("");
LuaString a = LuaString.valueOf("a");
LuaString ax = LuaString.valueOf("ax");
LuaString axb = LuaString.valueOf("axb");
LuaString axby = LuaString.valueOf("axby");
LuaString xbya = LuaString.valueOf("xbya");
LuaString bya = LuaString.valueOf("bya");
LuaString xby = LuaString.valueOf("xby");
LuaString axbya = LuaString.valueOf("axbya");
LuaValue nil = LuaValue.NIL;
assertEquals(nil, empty.invokemethod("match", args));
assertEquals(nil, a.invokemethod("match", args));
assertEquals(nil, ax.invokemethod("match", args));
assertEquals(nil, axb.invokemethod("match", args));
assertEquals(xby, axby.invokemethod("match", args));
assertEquals(xby, xbya.invokemethod("match", args));
assertEquals(nil, bya.invokemethod("match", args));
assertEquals(xby, xby.invokemethod("match", args));
assertEquals(xby, axbya.invokemethod("match", args));
assertEquals(xby, axbya.substring(0, 4).invokemethod("match", args));
assertEquals(nil, axbya.substring(0, 3).invokemethod("match", args));
assertEquals(xby, axbya.substring(1, 5).invokemethod("match", args));
assertEquals(nil, axbya.substring(2, 5).invokemethod("match", args));
}
}

View File

@@ -19,15 +19,19 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
package org.luaj.vm2;
package org.luaj.jse;
import junit.framework.TestCase;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.jse.JsePlatform;
public class UTF8StreamTest extends TestCase {
class UTF8StreamTest {
public void testUtf8CharsInStream() {
@Test
void testUtf8CharsInStream() {
String script = "x = \"98\u00b0: today's temp!\"\n" + "print('x = ', x)\n" + "return x";
Globals globals = JsePlatform.standardGlobals();
LuaValue chunk = globals.load(script);

View File

@@ -1,4 +1,4 @@
package org.luaj.vm2.require;
package org.luaj.jse.require;
import org.luaj.vm2.LuaValue;

View File

@@ -1,4 +1,4 @@
package org.luaj.vm2.require;
package org.luaj.jse.require;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.ZeroArgFunction;

View File

@@ -1,4 +1,4 @@
package org.luaj.vm2.require;
package org.luaj.jse.require;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.ZeroArgFunction;

View File

@@ -1,4 +1,4 @@
package org.luaj.vm2.require;
package org.luaj.jse.require;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.TwoArgFunction;

View File

@@ -1,13 +1,15 @@
package org.luaj.vm2.lib.jse;
import junit.framework.TestCase;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;
public class JsePlatformTest extends TestCase {
public void testLuaMainPassesArguments() {
class JsePlatformTest {
@Test
void testLuaMainPassesArguments() {
Globals globals = JsePlatform.standardGlobals();
LuaValue chunk = globals.load("return #arg, arg.n, arg[2], arg[1]");
Varargs results = JsePlatform.luaMain(chunk, new String[] { "aaa", "bbb" });

View File

@@ -1,16 +1,22 @@
package org.luaj.vm2.lib.jse;
import junit.framework.TestCase;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.LuaError;
import org.luaj.vm2.LuaInteger;
import org.luaj.vm2.LuaString;
import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;
import org.luaj.vm2.lib.MathLib;
public class LuaJavaCoercionTest extends TestCase {
class LuaJavaCoercionTest {
private static LuaValue globals;
private static LuaValue ZERO = LuaValue.ZERO;
@@ -19,19 +25,21 @@ public class LuaJavaCoercionTest extends TestCase {
private static LuaValue THREE = LuaValue.valueOf(3);
private static LuaString LENGTH = LuaString.valueOf("length");
@BeforeEach
protected void setUp() throws Exception {
super.setUp();
globals = JsePlatform.standardGlobals();
}
public void testJavaIntToLuaInt() {
@Test
void testJavaIntToLuaInt() {
Integer i = Integer.valueOf(777);
LuaValue v = CoerceJavaToLua.coerce(i);
assertEquals(LuaInteger.class, v.getClass());
assertEquals(777, v.toint());
}
public void testLuaIntToJavaInt() {
@Test
void testLuaIntToJavaInt() {
LuaInteger i = LuaInteger.valueOf(777);
Object o = CoerceLuaToJava.coerce(i, int.class);
assertEquals(Integer.class, o.getClass());
@@ -41,21 +49,24 @@ public class LuaJavaCoercionTest extends TestCase {
assertEquals(new Integer(777), o);
}
public void testJavaStringToLuaString() {
@Test
void testJavaStringToLuaString() {
String s = new String("777");
LuaValue v = CoerceJavaToLua.coerce(s);
assertEquals(LuaString.class, v.getClass());
assertEquals("777", v.toString());
}
public void testLuaStringToJavaString() {
@Test
void testLuaStringToJavaString() {
LuaString s = LuaValue.valueOf("777");
Object o = CoerceLuaToJava.coerce(s, String.class);
assertEquals(String.class, o.getClass());
assertEquals("777", o);
}
public void testJavaClassToLuaUserdata() {
@Test
void testJavaClassToLuaUserdata() {
LuaValue va = CoerceJavaToLua.coerce(ClassA.class);
LuaValue va1 = CoerceJavaToLua.coerce(ClassA.class);
LuaValue vb = CoerceJavaToLua.coerce(ClassB.class);
@@ -79,7 +90,8 @@ public class LuaJavaCoercionTest extends TestCase {
static class ClassB {
}
public void testJavaIntArrayToLuaTable() {
@Test
void testJavaIntArrayToLuaTable() {
int[] i = { 222, 333 };
LuaValue v = CoerceJavaToLua.coerce(i);
assertEquals(JavaArray.class, v.getClass());
@@ -108,7 +120,8 @@ public class LuaJavaCoercionTest extends TestCase {
}
}
public void testLuaTableToJavaIntArray() {
@Test
void testLuaTableToJavaIntArray() {
LuaTable t = new LuaTable();
t.set(1, LuaInteger.valueOf(222));
t.set(2, LuaInteger.valueOf(333));
@@ -121,7 +134,8 @@ public class LuaJavaCoercionTest extends TestCase {
assertEquals(333, i[1]);
}
public void testIntArrayScoringTables() {
@Test
void testIntArrayScoringTables() {
int a = 5;
LuaValue la = LuaInteger.valueOf(a);
LuaTable tb = new LuaTable();
@@ -146,7 +160,8 @@ public class LuaJavaCoercionTest extends TestCase {
assertTrue(scc < scb);
}
public void testIntArrayScoringUserdata() {
@Test
void testIntArrayScoringUserdata() {
int a = 5;
int[] b = { 44, 66 };
int[][] c = { { 11, 22 }, { 33, 44 } };
@@ -183,27 +198,31 @@ public class LuaJavaCoercionTest extends TestCase {
}
}
public void testMatchVoidArgs() {
@Test
void testMatchVoidArgs() {
LuaValue v = CoerceJavaToLua.coerce(new SampleClass());
LuaValue result = v.method("sample");
assertEquals("void-args", result.toString());
}
public void testMatchIntArgs() {
@Test
void testMatchIntArgs() {
LuaValue v = CoerceJavaToLua.coerce(new SampleClass());
LuaValue arg = CoerceJavaToLua.coerce(new Integer(123));
LuaValue result = v.method("sample", arg);
assertEquals("int-args 123", result.toString());
}
public void testMatchIntArrayArgs() {
@Test
void testMatchIntArrayArgs() {
LuaValue v = CoerceJavaToLua.coerce(new SampleClass());
LuaValue arg = CoerceJavaToLua.coerce(new int[] { 345, 678 });
LuaValue result = v.method("sample", arg);
assertEquals("int-array-args 345,678", result.toString());
}
public void testMatchIntArrayArrayArgs() {
@Test
void testMatchIntArrayArrayArgs() {
LuaValue v = CoerceJavaToLua.coerce(new SampleClass());
LuaValue arg = CoerceJavaToLua.coerce(new int[][] { { 22, 33 }, { 44, 55 } });
LuaValue result = v.method("sample", arg);
@@ -222,7 +241,8 @@ public class LuaJavaCoercionTest extends TestCase {
}
}
public void testExceptionMessage() {
@Test
void testExceptionMessage() {
String script = "local c = luajava.bindClass( \"" + SomeClass.class.getName() + "\" )\n"
+ "return pcall( c.someMethod, c )";
Varargs vresult = globals.get("load").call(LuaValue.valueOf(script)).invoke(LuaValue.NONE);
@@ -230,10 +250,11 @@ public class LuaJavaCoercionTest extends TestCase {
LuaValue message = vresult.arg(2);
assertEquals(LuaValue.FALSE, status);
int index = message.toString().indexOf("this is some message");
assertTrue("bad message: " + message, index >= 0);
assertTrue(index >= 0, "bad message: " + message);
}
public void testLuaErrorCause() {
@Test
void testLuaErrorCause() {
String script = "luajava.bindClass( \"" + SomeClass.class.getName() + "\"):someMethod()";
LuaValue chunk = globals.get("load").call(LuaValue.valueOf(script));
try {
@@ -251,7 +272,8 @@ public class LuaJavaCoercionTest extends TestCase {
public String arrayargsMethod(String a, String[] v);
}
public void testVarArgsProxy() {
@Test
void testVarArgsProxy() {
String script = "return luajava.createProxy( \"" + VarArgsInterface.class.getName() + "\", \n" + "{\n"
+ " varargsMethod = function(a,...)\n" + " return table.concat({a,...},'-')\n" + " end,\n"
+ " arrayargsMethod = function(a,array)\n" + " return tostring(a)..(array and \n"
@@ -273,7 +295,8 @@ public class LuaJavaCoercionTest extends TestCase {
assertEquals("foo-nil", v.arrayargsMethod("foo", null));
}
public void testBigNum() {
@Test
void testBigNum() {
String script = "bigNumA = luajava.newInstance('java.math.BigDecimal','12345678901234567890');\n"
+ "bigNumB = luajava.newInstance('java.math.BigDecimal','12345678901234567890');\n"
+ "bigNumC = bigNumA:multiply(bigNumB);\n" +
@@ -389,29 +412,41 @@ public class LuaJavaCoercionTest extends TestCase {
public static class D extends C implements IA {
}
public void testOverloadedJavaMethodObject() { doOverloadedMethodTest("Object", ""); }
@Test
void testOverloadedJavaMethodObject() { doOverloadedMethodTest("Object", ""); }
public void testOverloadedJavaMethodString() { doOverloadedMethodTest("String", "abc"); }
@Test
void testOverloadedJavaMethodString() { doOverloadedMethodTest("String", "abc"); }
public void testOverloadedJavaMethodA() { doOverloadedMethodTest("A", ""); }
@Test
void testOverloadedJavaMethodA() { doOverloadedMethodTest("A", ""); }
public void testOverloadedJavaMethodB() { doOverloadedMethodTest("B", ""); }
@Test
void testOverloadedJavaMethodB() { doOverloadedMethodTest("B", ""); }
public void testOverloadedJavaMethodC() { doOverloadedMethodTest("C", ""); }
@Test
void testOverloadedJavaMethodC() { doOverloadedMethodTest("C", ""); }
public void testOverloadedJavaMethodByte() { doOverloadedMethodTest("byte", "1"); }
@Test
void testOverloadedJavaMethodByte() { doOverloadedMethodTest("byte", "1"); }
public void testOverloadedJavaMethodChar() { doOverloadedMethodTest("char", "65000"); }
@Test
void testOverloadedJavaMethodChar() { doOverloadedMethodTest("char", "65000"); }
public void testOverloadedJavaMethodShort() { doOverloadedMethodTest("short", "-32000"); }
@Test
void testOverloadedJavaMethodShort() { doOverloadedMethodTest("short", "-32000"); }
public void testOverloadedJavaMethodInt() { doOverloadedMethodTest("int", "100000"); }
@Test
void testOverloadedJavaMethodInt() { doOverloadedMethodTest("int", "100000"); }
public void testOverloadedJavaMethodLong() { doOverloadedMethodTest("long", "50000000000"); }
@Test
void testOverloadedJavaMethodLong() { doOverloadedMethodTest("long", "50000000000"); }
public void testOverloadedJavaMethodFloat() { doOverloadedMethodTest("float", "6.5"); }
@Test
void testOverloadedJavaMethodFloat() { doOverloadedMethodTest("float", "6.5"); }
public void testOverloadedJavaMethodDouble() { doOverloadedMethodTest("double", "3.141592653589793"); }
@Test
void testOverloadedJavaMethodDouble() { doOverloadedMethodTest("double", "3.141592653589793"); }
private void doOverloadedMethodTest(String typename, String value) {
String script = "local a = luajava.newInstance('" + B.class.getName() + "');\n" + "local b = a:set(a:get"
@@ -430,7 +465,8 @@ public class LuaJavaCoercionTest extends TestCase {
assertEquals("setr(" + typename + ") " + value, sc);
}
public void testClassInheritanceLevels() {
@Test
void testClassInheritanceLevels() {
assertEquals(0, CoerceLuaToJava.inheritanceLevels(Object.class, Object.class));
assertEquals(1, CoerceLuaToJava.inheritanceLevels(Object.class, String.class));
assertEquals(1, CoerceLuaToJava.inheritanceLevels(Object.class, A.class));
@@ -456,7 +492,8 @@ public class LuaJavaCoercionTest extends TestCase {
assertEquals(0, CoerceLuaToJava.inheritanceLevels(C.class, C.class));
}
public void testInterfaceInheritanceLevels() {
@Test
void testInterfaceInheritanceLevels() {
assertEquals(1, CoerceLuaToJava.inheritanceLevels(IA.class, A.class));
assertEquals(1, CoerceLuaToJava.inheritanceLevels(IB.class, B.class));
assertEquals(2, CoerceLuaToJava.inheritanceLevels(IA.class, B.class));
@@ -474,7 +511,8 @@ public class LuaJavaCoercionTest extends TestCase {
assertEquals(1, CoerceLuaToJava.inheritanceLevels(IA.class, IB.class));
}
public void testCoerceJavaToLuaLuaValue() {
@Test
void testCoerceJavaToLuaLuaValue() {
assertSame(LuaValue.NIL, CoerceJavaToLua.coerce(LuaValue.NIL));
assertSame(LuaValue.ZERO, CoerceJavaToLua.coerce(LuaValue.ZERO));
assertSame(LuaValue.ONE, CoerceJavaToLua.coerce(LuaValue.ONE));
@@ -483,7 +521,8 @@ public class LuaJavaCoercionTest extends TestCase {
assertSame(table, CoerceJavaToLua.coerce(table));
}
public void testCoerceJavaToLuaByeArray() {
@Test
void testCoerceJavaToLuaByeArray() {
byte[] bytes = "abcd".getBytes();
LuaValue value = CoerceJavaToLua.coerce(bytes);
assertEquals(LuaString.class, value.getClass());

View File

@@ -1,16 +1,19 @@
package org.luaj.vm2.lib.jse;
import junit.framework.TestCase;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaValue;
public class LuajavaAccessibleMembersTest extends TestCase {
class LuajavaAccessibleMembersTest {
private Globals globals;
@BeforeEach
protected void setUp() throws Exception {
super.setUp();
globals = JsePlatform.standardGlobals();
}
@@ -24,33 +27,39 @@ public class LuajavaAccessibleMembersTest extends TestCase {
}
}
public void testAccessFromPrivateClassImplementedMethod() {
@Test
void testAccessFromPrivateClassImplementedMethod() {
assertEquals("privateImpl-aaa-interface_method(bar)",
invokeScript("b = luajava.newInstance('" + TestClass.class.getName() + "');"
+ "a = b:create_PrivateImpl('aaa');" + "return a:interface_method('bar');"));
}
public void testAccessFromPrivateClassPublicMethod() {
@Test
void testAccessFromPrivateClassPublicMethod() {
assertEquals("privateImpl-aaa-public_method", invokeScript("b = luajava.newInstance('"
+ TestClass.class.getName() + "');" + "a = b:create_PrivateImpl('aaa');" + "return a:public_method();"));
}
public void testAccessFromPrivateClassGetPublicField() {
@Test
void testAccessFromPrivateClassGetPublicField() {
assertEquals("aaa", invokeScript("b = luajava.newInstance('" + TestClass.class.getName() + "');"
+ "a = b:create_PrivateImpl('aaa');" + "return a.public_field;"));
}
public void testAccessFromPrivateClassSetPublicField() {
@Test
void testAccessFromPrivateClassSetPublicField() {
assertEquals("foo", invokeScript("b = luajava.newInstance('" + TestClass.class.getName() + "');"
+ "a = b:create_PrivateImpl('aaa');" + "a.public_field = 'foo';" + "return a.public_field;"));
}
public void testAccessFromPrivateClassPublicConstructor() {
@Test
void testAccessFromPrivateClassPublicConstructor() {
assertEquals("privateImpl-constructor", invokeScript("b = luajava.newInstance('" + TestClass.class.getName()
+ "');" + "c = b:get_PrivateImplClass();" + "return luajava.new(c);"));
}
public void testAccessPublicEnum() {
@Test
void testAccessPublicEnum() {
assertEquals("class org.luaj.vm2.lib.jse.TestClass$SomeEnum",
invokeScript("b = luajava.newInstance('" + TestClass.class.getName() + "');" + "return b.SomeEnum"));
}

View File

@@ -1,11 +1,16 @@
package org.luaj.vm2.lib.jse;
import junit.framework.TestCase;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.LuaError;
import org.luaj.vm2.LuaValue;
public class LuajavaClassMembersTest extends TestCase {
class LuajavaClassMembersTest {
public static class A {
protected A() {}
}
@@ -66,10 +71,13 @@ public class LuajavaClassMembersTest extends TestCase {
public C(String s, int i) { m_string_field = s; m_int_field = i; }
@Override
public int getint() { return 200000; }
@Override
public String pick(String s) { return "class-c-pick(string:" + s + ")"; }
@Override
public String pick(int i) { return "class-c-pick(int:" + i + ")"; }
public static class D {
@@ -87,7 +95,8 @@ public class LuajavaClassMembersTest extends TestCase {
static LuaValue SOMEB = CoerceJavaToLua.coerce(new B());
static LuaValue SOMEC = CoerceJavaToLua.coerce(new C());
public void testSetByteField() {
@Test
void testSetByteField() {
B b = new B();
JavaInstance i = new JavaInstance(b);
i.set("m_byte_field", ONE);
@@ -101,7 +110,8 @@ public class LuajavaClassMembersTest extends TestCase {
assertEquals(ZERO, i.get("m_byte_field"));
}
public void testSetDoubleField() {
@Test
void testSetDoubleField() {
B b = new B();
JavaInstance i = new JavaInstance(b);
i.set("m_double_field", ONE);
@@ -115,7 +125,8 @@ public class LuajavaClassMembersTest extends TestCase {
assertEquals(ZERO, i.get("m_double_field"));
}
public void testNoFactory() {
@Test
void testNoFactory() {
JavaClass c = JavaClass.forClass(A.class);
try {
c.call();
@@ -124,7 +135,8 @@ public class LuajavaClassMembersTest extends TestCase {
}
}
public void testUniqueFactoryCoercible() {
@Test
void testUniqueFactoryCoercible() {
JavaClass c = JavaClass.forClass(B.class);
assertEquals(JavaClass.class, c.getClass());
LuaValue constr = c.get("new");
@@ -138,7 +150,8 @@ public class LuajavaClassMembersTest extends TestCase {
assertEquals(0, ((B) b0).m_int_field);
}
public void testUniqueFactoryUncoercible() {
@Test
void testUniqueFactoryUncoercible() {
JavaClass f = JavaClass.forClass(B.class);
LuaValue constr = f.get("new");
assertEquals(JavaConstructor.class, constr.getClass());
@@ -151,7 +164,8 @@ public class LuajavaClassMembersTest extends TestCase {
}
}
public void testOverloadedFactoryCoercible() {
@Test
void testOverloadedFactoryCoercible() {
JavaClass f = JavaClass.forClass(C.class);
LuaValue constr = f.get("new");
assertEquals(JavaConstructor.Overload.class, constr.getClass());
@@ -173,7 +187,8 @@ public class LuajavaClassMembersTest extends TestCase {
assertEquals(456, ((C) csi).m_int_field);
}
public void testOverloadedFactoryUncoercible() {
@Test
void testOverloadedFactoryUncoercible() {
JavaClass f = JavaClass.forClass(C.class);
try {
Object c = f.call(LuaValue.userdataOf(new Object()));
@@ -184,7 +199,8 @@ public class LuajavaClassMembersTest extends TestCase {
}
}
public void testNoAttribute() {
@Test
void testNoAttribute() {
JavaClass f = JavaClass.forClass(A.class);
LuaValue v = f.get("bogus");
assertEquals(v, LuaValue.NIL);
@@ -195,7 +211,8 @@ public class LuajavaClassMembersTest extends TestCase {
}
}
public void testFieldAttributeCoercible() {
@Test
void testFieldAttributeCoercible() {
JavaInstance i = new JavaInstance(new B());
i.set("m_int_field", ONE);
assertEquals(1, i.get("m_int_field").toint());
@@ -208,7 +225,8 @@ public class LuajavaClassMembersTest extends TestCase {
assertEquals(3, i.get("m_int_field").toint());
}
public void testUniqueMethodAttributeCoercible() {
@Test
void testUniqueMethodAttributeCoercible() {
B b = new B();
JavaInstance ib = new JavaInstance(b);
LuaValue b_getString = ib.get("getString");
@@ -221,7 +239,8 @@ public class LuajavaClassMembersTest extends TestCase {
assertEquals(200000, b_getint.call(SOMEC).toint());
}
public void testUniqueMethodAttributeArgsCoercible() {
@Test
void testUniqueMethodAttributeArgsCoercible() {
B b = new B();
JavaInstance ib = new JavaInstance(b);
LuaValue uniq = ib.get("uniq");
@@ -243,7 +262,8 @@ public class LuajavaClassMembersTest extends TestCase {
uniqis.invoke(LuaValue.varargsOf(new LuaValue[] { SOMEB, ONE, ABC, ONE })).arg1().tojstring());
}
public void testOverloadedMethodAttributeCoercible() {
@Test
void testOverloadedMethodAttributeCoercible() {
B b = new B();
JavaInstance ib = new JavaInstance(b);
LuaValue p = ib.get("pick");
@@ -256,7 +276,8 @@ public class LuajavaClassMembersTest extends TestCase {
p.invoke(LuaValue.varargsOf(new LuaValue[] { SOMEB, ONE, ABC, ONE })).arg1().tojstring());
}
public void testUnboundOverloadedMethodAttributeCoercible() {
@Test
void testUnboundOverloadedMethodAttributeCoercible() {
B b = new B();
JavaInstance ib = new JavaInstance(b);
LuaValue p = ib.get("pick");
@@ -270,7 +291,8 @@ public class LuajavaClassMembersTest extends TestCase {
p.invoke(LuaValue.varargsOf(new LuaValue[] { SOMEC, ONE, ABC, ONE })).arg1().tojstring());
}
public void testOverloadedStaticMethodAttributeCoercible() {
@Test
void testOverloadedStaticMethodAttributeCoercible() {
B b = new B();
JavaInstance ib = new JavaInstance(b);
LuaValue p = ib.get("staticpick");
@@ -283,7 +305,8 @@ public class LuajavaClassMembersTest extends TestCase {
p.invoke(LuaValue.varargsOf(new LuaValue[] { SOMEB, ONE, ABC, ONE })).arg1().tojstring());
}
public void testGetInnerClass() {
@Test
void testGetInnerClass() {
C c = new C();
JavaInstance ic = new JavaInstance(c);
LuaValue d = ic.get("D");

View File

@@ -0,0 +1,138 @@
package org.luaj.vm2.lib.jse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import java.util.Date;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.LuaValue;
class OsLibTest {
LuaValue jse_lib;
double time;
@BeforeEach
public void setUp() {
jse_lib = JsePlatform.standardGlobals().get("os");
time = new Date(2001-1900, 7, 23, 14, 55, 02).getTime()/1000.0;
}
private void test(String format, String expected) {
String actual = jse_lib.get("date").call(LuaValue.valueOf(format), LuaValue.valueOf(time)).tojstring();
assertEquals(expected, actual);
}
@Test
void testStringDateChars() { test("foo", "foo"); }
@Test
void testStringDate_a() { test("%a", "Thu"); }
@Test
void testStringDate_A() { test("%A", "Thursday"); }
@Test
void testStringDate_b() { test("%b", "Aug"); }
@Test
void testStringDate_B() { test("%B", "August"); }
@Test
void testStringDate_c() { test("%c", "Thu Aug 23 14:55:02 2001"); }
@Test
void testStringDate_d() { test("%d", "23"); }
@Test
void testStringDate_H() { test("%H", "14"); }
@Test
void testStringDate_I() { test("%I", "02"); }
@Test
void testStringDate_j() { test("%j", "235"); }
@Test
void testStringDate_m() { test("%m", "08"); }
@Test
void testStringDate_M() { test("%M", "55"); }
@Test
void testStringDate_p() { test("%p", "PM"); }
@Test
void testStringDate_S() { test("%S", "02"); }
@Test
void testStringDate_U() { test("%U", "33"); }
@Test
void testStringDate_w() { test("%w", "4"); }
@Test
void testStringDate_W() { test("%W", "34"); }
@Test
void testStringDate_x() { test("%x", "08/23/01"); }
@Test
void testStringDate_X() { test("%X", "14:55:02"); }
@Test
void testStringDate_y() { test("%y", "01"); }
@Test
void testStringDate_Y() { test("%Y", "2001"); }
@Test
void testStringDate_Pct() { test("%%", "%"); }
static final double DAY = 24.*3600.;
@Test
void testStringDate_UW_neg4() { time -= 4*DAY; test("%c %U %W", "Sun Aug 19 14:55:02 2001 33 33"); }
@Test
void testStringDate_UW_neg3() { time -= 3*DAY; test("%c %U %W", "Mon Aug 20 14:55:02 2001 33 34"); }
@Test
void testStringDate_UW_neg2() { time -= 2*DAY; test("%c %U %W", "Tue Aug 21 14:55:02 2001 33 34"); }
@Test
void testStringDate_UW_neg1() { time -= DAY; test("%c %U %W", "Wed Aug 22 14:55:02 2001 33 34"); }
@Test
void testStringDate_UW_pos0() { time += 0; test("%c %U %W", "Thu Aug 23 14:55:02 2001 33 34"); }
@Test
void testStringDate_UW_pos1() { time += DAY; test("%c %U %W", "Fri Aug 24 14:55:02 2001 33 34"); }
@Test
void testStringDate_UW_pos2() { time += 2*DAY; test("%c %U %W", "Sat Aug 25 14:55:02 2001 33 34"); }
@Test
void testStringDate_UW_pos3() { time += 3*DAY; test("%c %U %W", "Sun Aug 26 14:55:02 2001 34 34"); }
@Test
void testStringDate_UW_pos4() { time += 4*DAY; test("%c %U %W", "Mon Aug 27 14:55:02 2001 34 35"); }
@Test
void testJseOsGetenvForEnvVariables() {
LuaValue USER = LuaValue.valueOf("USER");
LuaValue jse_user = jse_lib.get("getenv").call(USER);
assertFalse(jse_user.isnil());
}
@Test
void testJseOsGetenvForSystemProperties() {
System.setProperty("test.key.foo", "test.value.bar");
LuaValue key = LuaValue.valueOf("test.key.foo");
LuaValue value = LuaValue.valueOf("test.value.bar");
LuaValue jse_value = jse_lib.get("getenv").call(key);
assertEquals(value, jse_value);
}
}

View File

@@ -0,0 +1,27 @@
package org.luaj.vm2.script;
import static org.junit.jupiter.api.Assertions.assertTrue;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.LuaValue;
class CompileClosureTest extends DefaultBindingsTestCase {
@BeforeEach
@Override
protected void setUp() throws Exception {
System.setProperty("org.luaj.luajc", "false");
super.setUp();
}
@Test
void testCompiledFunctionIsClosure() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("return 'foo'");
LuaValue value = ((LuaScriptEngine.LuajCompiledScript) cs).function;
assertTrue(value.isclosure());
}
}

View File

@@ -0,0 +1,27 @@
package org.luaj.vm2.script;
import static org.junit.jupiter.api.Assertions.assertFalse;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.LuaValue;
class CompileNonClosureTest extends DefaultBindingsTestCase {
@BeforeEach
@Override
protected void setUp() throws Exception {
System.setProperty("org.luaj.luajc", "true");
super.setUp();
}
@Test
void testCompiledFunctionIsNotClosure() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("return 'foo'");
LuaValue value = ((LuaScriptEngine.LuajCompiledScript) cs).function;
assertFalse(value.isclosure());
}
}

View File

@@ -0,0 +1,10 @@
package org.luaj.vm2.script;
import javax.script.Bindings;
abstract class DefaultBindingsTestCase extends EngineTestCase {
@Override
protected Bindings createBindings() {
return e.createBindings();
}
}

View File

@@ -0,0 +1,186 @@
package org.luaj.vm2.script;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.Reader;
import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.LuaFunction;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.OneArgFunction;
abstract class EngineTestCase {
protected ScriptEngine e;
protected Bindings b;
protected abstract Bindings createBindings();
@BeforeEach
protected void setUp() throws Exception {
this.e = new ScriptEngineManager().getEngineByName("luaj");
this.b = createBindings();
}
@Test
void testSqrtIntResult() throws ScriptException {
e.put("x", 25);
e.eval("y = math.sqrt(x)");
Object y = e.get("y");
assertEquals(5, y);
}
@Test
void testOneArgFunction() throws ScriptException {
e.put("x", 25);
e.eval("y = math.sqrt(x)");
Object y = e.get("y");
assertEquals(5, y);
e.put("f", new OneArgFunction() {
@Override
public LuaValue call(LuaValue arg) {
return LuaValue.valueOf(arg.toString() + "123");
}
});
Object r = e.eval("return f('abc')");
assertEquals("abc123", r);
}
@Test
void testCompiledScript() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("y = math.sqrt(x); return y");
b.put("x", 144);
assertEquals(12, cs.eval(b));
}
@Test
void testBuggyLuaScript() {
try {
e.eval("\n\nbuggy lua code\n\n");
} catch (ScriptException se) {
assertEquals("eval threw javax.script.ScriptException: [string \"script\"]:3: syntax error",
se.getMessage());
return;
}
fail("buggy script did not throw ScriptException as expected.");
}
@Test
void testScriptRedirection() throws ScriptException {
Reader input = new CharArrayReader("abcdefg\nhijk".toCharArray());
CharArrayWriter output = new CharArrayWriter();
CharArrayWriter errors = new CharArrayWriter();
String script = "print(\"string written using 'print'\")\n"
+ "io.write(\"string written using 'io.write()'\\n\")\n"
+ "io.stdout:write(\"string written using 'io.stdout:write()'\\n\")\n"
+ "io.stderr:write(\"string written using 'io.stderr:write()'\\n\")\n"
+ "io.write([[string read using 'io.stdin:read(\"*l\")':]]..io.stdin:read(\"*l\")..\"\\n\")\n";
// Evaluate script with redirection set
e.getContext().setReader(input);
e.getContext().setWriter(output);
e.getContext().setErrorWriter(errors);
e.eval(script);
final String expectedOutput = "string written using 'print'\n" + "string written using 'io.write()'\n"
+ "string written using 'io.stdout:write()'\n" + "string read using 'io.stdin:read(\"*l\")':abcdefg\n";
assertEquals(expectedOutput, output.toString());
final String expectedErrors = "string written using 'io.stderr:write()'\n";
assertEquals(expectedErrors, errors.toString());
// Evaluate script with redirection reset
output.reset();
errors.reset();
// e.getContext().setReader(null); // This will block if using actual STDIN
e.getContext().setWriter(null);
e.getContext().setErrorWriter(null);
e.eval(script);
assertEquals("", output.toString());
assertEquals("", errors.toString());
}
@Test
void testBindingJavaInt() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("y = x; return 'x '..type(x)..' '..tostring(x)\n");
b.put("x", 111);
assertEquals("x number 111", cs.eval(b));
assertEquals(111, b.get("y"));
}
@Test
void testBindingJavaDouble() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("y = x; return 'x '..type(x)..' '..tostring(x)\n");
b.put("x", 125.125);
assertEquals("x number 125.125", cs.eval(b));
assertEquals(125.125, b.get("y"));
}
@Test
void testBindingJavaString() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("y = x; return 'x '..type(x)..' '..tostring(x)\n");
b.put("x", "foo");
assertEquals("x string foo", cs.eval(b));
assertEquals("foo", b.get("y"));
}
@Test
void testBindingJavaObject() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("y = x; return 'x '..type(x)..' '..tostring(x)\n");
b.put("x", new SomeUserClass());
assertEquals("x userdata some-user-value", cs.eval(b));
assertEquals(SomeUserClass.class, b.get("y").getClass());
}
@Test
void testBindingJavaArray() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("y = x; return 'x '..type(x)..' '..#x..' '..x[1]..' '..x[2]\n");
b.put("x", new int[] { 777, 888 });
assertEquals("x userdata 2 777 888", cs.eval(b));
assertEquals(int[].class, b.get("y").getClass());
}
@Test
void testBindingLuaFunction() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("y = function(x) return 678 + x end; return 'foo'");
assertEquals("foo", cs.eval(b).toString());
assertTrue(b.get("y") instanceof LuaFunction);
assertEquals(LuaValue.valueOf(801), ((LuaFunction) b.get("y")).call(LuaValue.valueOf(123)));
}
@Test
void testUserClasses() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("x = x or luajava.newInstance('java.lang.String', 'test')\n"
+ "return 'x ' .. type(x) .. ' ' .. tostring(x)\n");
assertEquals("x string test", cs.eval(b));
b.put("x", new SomeUserClass());
assertEquals("x userdata some-user-value", cs.eval(b));
}
@Test
void testReturnMultipleValues() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("return 'foo', 'bar'\n");
Object o = cs.eval();
assertEquals(Object[].class, o.getClass());
Object[] array = (Object[]) o;
assertEquals(2, array.length);
assertEquals("foo", array[0]);
assertEquals("bar", array[1]);
}
private static class SomeUserClass {
@Override
public String toString() {
return "some-user-value";
}
}
}

View File

@@ -0,0 +1,43 @@
package org.luaj.vm2.script;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import org.junit.jupiter.api.Test;
class LookupEngineTest {
@Test
void testGetEngineByExtension() {
ScriptEngine e = new ScriptEngineManager().getEngineByExtension(".lua");
assertNotNull(e);
assertEquals(LuaScriptEngine.class, e.getClass());
}
@Test
void testGetEngineByName() {
ScriptEngine e = new ScriptEngineManager().getEngineByName("luaj");
assertNotNull(e);
assertEquals(LuaScriptEngine.class, e.getClass());
}
@Test
void testGetEngineByMimeType() {
ScriptEngine e = new ScriptEngineManager().getEngineByMimeType("text/lua");
assertNotNull(e);
assertEquals(LuaScriptEngine.class, e.getClass());
}
@Test
void testFactoryMetadata() {
ScriptEngine e = new ScriptEngineManager().getEngineByName("luaj");
ScriptEngineFactory f = e.getFactory();
assertEquals("Luaj", f.getEngineName());
assertEquals("Luaj 0.0", f.getEngineVersion());
assertEquals("lua", f.getLanguageName());
assertEquals("5.2", f.getLanguageVersion());
}
}

View File

@@ -0,0 +1,11 @@
package org.luaj.vm2.script;
import javax.script.Bindings;
import javax.script.SimpleBindings;
class SimpleBindingsTest extends EngineTestCase {
@Override
protected Bindings createBindings() {
return new SimpleBindings();
}
}

View File

@@ -0,0 +1,55 @@
package org.luaj.vm2.script;
import static org.junit.jupiter.api.Assertions.assertEquals;
import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class UserContextTest {
protected ScriptEngine e;
protected Bindings b;
protected ScriptContext c;
@BeforeEach
public void setUp() {
this.e = new ScriptEngineManager().getEngineByName("luaj");
this.c = new LuajContext();
this.b = c.getBindings(ScriptContext.ENGINE_SCOPE);
}
@Test
void testUncompiledScript() throws ScriptException {
b.put("x", 144);
assertEquals(12, e.eval("z = math.sqrt(x); return z", b));
assertEquals(12, b.get("z"));
assertEquals(null, e.getBindings(ScriptContext.ENGINE_SCOPE).get("z"));
assertEquals(null, e.getBindings(ScriptContext.GLOBAL_SCOPE).get("z"));
b.put("x", 25);
assertEquals(5, e.eval("z = math.sqrt(x); return z", c));
assertEquals(5, b.get("z"));
assertEquals(null, e.getBindings(ScriptContext.ENGINE_SCOPE).get("z"));
assertEquals(null, e.getBindings(ScriptContext.GLOBAL_SCOPE).get("z"));
}
@Test
void testCompiledScript() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("z = math.sqrt(x); return z");
b.put("x", 144);
assertEquals(12, cs.eval(b));
assertEquals(12, b.get("z"));
b.put("x", 25);
assertEquals(5, cs.eval(c));
assertEquals(5, b.get("z"));
}
}

View File

@@ -0,0 +1,38 @@
package org.luaj.vm2.script;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.CharArrayWriter;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class WriterTest {
protected ScriptEngine e;
protected Bindings b;
@BeforeEach
public void setUp() {
this.e = new ScriptEngineManager().getEngineByName("luaj");
this.b = e.getBindings(ScriptContext.ENGINE_SCOPE);
}
@Test
void testWriter() throws ScriptException {
CharArrayWriter output = new CharArrayWriter();
CharArrayWriter errors = new CharArrayWriter();
e.getContext().setWriter(output);
e.getContext().setErrorWriter(errors);
e.eval("io.write( [[line]] )");
assertEquals("line", output.toString());
e.eval("io.write( [[ one\nline two\n]] )");
assertEquals("line one\nline two\n", output.toString());
output.reset();
}
}

View File

@@ -26,8 +26,20 @@
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.microemu</groupId>
<artifactId>microemulator</artifactId>
<version>2.0.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.microemu</groupId>
<artifactId>microemu-jsr-75</artifactId>
<version>2.0.4</version>
<scope>test</scope>
</dependency>
</dependencies>

View File

@@ -19,10 +19,19 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
package org.luaj.vm2;
import junit.framework.TestSuite;
package org.luaj;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.LuaBoolean;
import org.luaj.vm2.LuaFunction;
import org.luaj.vm2.LuaNil;
import org.luaj.vm2.LuaNumber;
import org.luaj.vm2.LuaString;
import org.luaj.vm2.LuaThread;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.luajc.LuaJC;
/**
@@ -31,24 +40,21 @@ import org.luaj.vm2.luajc.LuaJC;
* Results are compared for exact match with the installed C-based lua
* environment.
*/
public class CompatibiltyTest extends TestSuite {
public class CompatibiltyTest {
private static final String dir = "";
abstract protected static class CompatibiltyTestSuite extends ScriptDrivenTest {
abstract static class CompatibiltyTestCase extends PlatformTestCase {
LuaValue savedStringMetatable;
protected CompatibiltyTestSuite(PlatformType platform) {
super(platform, dir);
}
protected void setUp() throws Exception {
@BeforeEach
@Override
protected void setUp() {
savedStringMetatable = LuaString.s_metatable;
setBaseDir("compatibility");
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
@AfterEach
protected void tearDown() {
LuaNil.s_metatable = null;
LuaBoolean.s_metatable = null;
LuaNumber.s_metatable = null;
@@ -57,79 +63,94 @@ public class CompatibiltyTest extends TestSuite {
LuaString.s_metatable = savedStringMetatable;
}
public void testBaseLib() { runTest("baselib"); }
@Test
void testBaseLib() { runTest("baselib"); }
public void testCoroutineLib() { runTest("coroutinelib"); }
@Test
void testCoroutineLib() { runTest("coroutinelib"); }
public void testDebugLib() { runTest("debuglib"); }
@Test
void testDebugLib() { runTest("debuglib"); }
public void testErrors() { runTest("errors"); }
@Test
void testErrors() { runTest("errors"); }
public void testFunctions() { runTest("functions"); }
@Test
void testFunctions() { runTest("functions"); }
public void testIoLib() { runTest("iolib"); }
@Test
void testIoLib() { runTest("iolib"); }
public void testManyUpvals() { runTest("manyupvals"); }
@Test
void testManyUpvals() { runTest("manyupvals"); }
public void testMathLib() { runTest("mathlib"); }
@Test
void testMathLib() { runTest("mathlib"); }
public void testMetatags() { runTest("metatags"); }
@Test
void testMetatags() { runTest("metatags"); }
public void testOsLib() { runTest("oslib"); }
@Test
void testOsLib() { runTest("oslib"); }
public void testStringLib() { runTest("stringlib"); }
@Test
void testStringLib() { runTest("stringlib"); }
public void testTableLib() { runTest("tablelib"); }
@Test
void testTableLib() { runTest("tablelib"); }
public void testTailcalls() { runTest("tailcalls"); }
@Test
void testTailcalls() { runTest("tailcalls"); }
public void testUpvalues() { runTest("upvalues"); }
@Test
void testUpvalues() { runTest("upvalues"); }
public void testVm() { runTest("vm"); }
@Test
void testVm() { runTest("vm"); }
}
public static TestSuite suite() {
TestSuite suite = new TestSuite("Compatibility Tests");
suite.addTest(new TestSuite(JseCompatibilityTest.class, "JSE Compatibility Tests"));
suite.addTest(new TestSuite(JmeCompatibilityTest.class, "JME Compatibility Tests"));
suite.addTest(new TestSuite(LuaJCCompatibilityTest.class, "LuaJC Compatibility Tests"));
return suite;
}
@Nested
public static class JmeCompatibilityTest extends CompatibiltyTestCase {
public static class JmeCompatibilityTest extends CompatibiltyTestSuite {
public JmeCompatibilityTest() {
super(ScriptDrivenTest.PlatformType.JME);
}
protected void setUp() throws Exception {
@BeforeEach
@Override
protected void setUp() {
setPlatform(PlatformTestCase.PlatformType.JME);
System.setProperty("JME", "true");
super.setUp();
}
// Emulator cannot create files for writing
@Override
void testIoLib() {}
}
public static class JseCompatibilityTest extends CompatibiltyTestSuite {
public JseCompatibilityTest() {
super(ScriptDrivenTest.PlatformType.JSE);
}
@Nested
public static class JseCompatibilityTest extends CompatibiltyTestCase {
protected void setUp() throws Exception {
super.setUp();
@BeforeEach
@Override
protected void setUp() {
setPlatform(PlatformTestCase.PlatformType.JSE);
System.setProperty("JME", "false");
}
}
public static class LuaJCCompatibilityTest extends CompatibiltyTestSuite {
public LuaJCCompatibilityTest() {
super(ScriptDrivenTest.PlatformType.LUAJIT);
}
protected void setUp() throws Exception {
super.setUp();
}
}
@Nested
public static class LuaJCCompatibilityTest extends CompatibiltyTestCase {
@BeforeEach
@Override
protected void setUp() {
setPlatform(PlatformTestCase.PlatformType.LUAJIT);
System.setProperty("JME", "false");
super.setUp();
LuaJC.install(globals);
}
// not supported on this platform - don't test
public void testDebugLib() {}
@Override
void testDebugLib() {}
}
}

View File

@@ -0,0 +1,95 @@
package org.luaj;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class CompilerTest extends CompilingTestCase {
@BeforeEach
@Override
protected void setUp() {
setBaseDir("lua5.2.1-tests");
super.setUp();
}
@Test
void testAll() { doTest("all"); }
@Test
void testApi() { doTest("api"); }
@Test
void testAttrib() { doTest("attrib"); }
@Test
void testBig() { doTest("big"); }
@Test
void testBitwise() { doTest("bitwise"); }
@Test
void testCalls() { doTest("calls"); }
@Test
void testChecktable() { doTest("checktable"); }
@Test
void testClosure() { doTest("closure"); }
@Test
void testCode() { doTest("code"); }
@Test
void testConstruct() { doTest("constructs"); }
@Test
void testCoroutine() { doTest("coroutine"); }
@Test
void testDb() { doTest("db"); }
@Test
void testErrors() { doTest("errors"); }
@Test
void testEvents() { doTest("events"); }
@Test
void testFiles() { doTest("files"); }
@Test
void testGc() { doTest("gc"); }
@Test
void testGoto() { doTest("goto"); }
@Test
void testLiterals() { doTest("literals"); }
@Test
void testLocals() { doTest("locals"); }
@Test
void testMain() { doTest("main"); }
@Test
void testMath() { doTest("math"); }
@Test
void testNextvar() { doTest("nextvar"); }
@Test
void testPm() { doTest("pm"); }
@Test
void testSort() { doTest("sort"); }
@Test
void testStrings() { doTest("strings"); }
@Test
void testVararg() { doTest("vararg"); }
@Test
void testVerybig() { doTest("verybig"); }
}

View File

@@ -0,0 +1,53 @@
package org.luaj;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.luaj.vm2.Print;
import org.luaj.vm2.Prototype;
import org.luaj.vm2.compiler.DumpState;
abstract class CompilingTestCase extends ResourcesTestCase {
protected void doTest(String name) {
try {
// compile in memory
Prototype p = globals.loadPrototype(inputStreamOfLua(name), "@" + name + ".lua", "bt");
String actual = protoToString(p);
// load expected value from jar
Prototype e = globals.loadPrototype(inputStreamOfBytecode(name), name, "b");
String expected = protoToString(e);
// compare results
assertEquals(expected, actual);
// dump into memory
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DumpState.dump(p, baos, false);
ByteArrayInputStream dumped = new ByteArrayInputStream(baos.toByteArray());
// re-undump
Prototype p2 = globals.loadPrototype(dumped, name, "b");
String actual2 = protoToString(p2);
// compare again
assertEquals(actual, actual2);
} catch (Exception e) {
fail(e.toString());
}
}
private String protoToString(Prototype p) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
Print.ps = ps;
Print.printFunction(p, true);
return baos.toString();
}
}

View File

@@ -19,31 +19,34 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
package org.luaj.vm2;
package org.luaj;
import java.io.IOException;
import java.io.InputStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Test argument type check errors
*
* Results are compared for exact match with the installed C-based lua
* environment.
*/
public class ErrorsTest extends ScriptDrivenTest {
class ErrorsTest extends PlatformTestCase {
private static final String dir = "errors/";
public ErrorsTest() {
super(ScriptDrivenTest.PlatformType.JSE, dir);
}
protected void setUp() throws Exception {
@BeforeEach
@Override
protected void setUp() {
setBaseDir("errors");
setPlatform(PlatformTestCase.PlatformType.JSE);
super.setUp();
}
public void testBaseLibArgs() {
@Test
void testBaseLibArgs() {
globals.STDIN = new InputStream() {
@Override
public int read() throws IOException {
return -1;
}
@@ -51,20 +54,28 @@ public class ErrorsTest extends ScriptDrivenTest {
runTest("baselibargs");
}
public void testCoroutineLibArgs() { runTest("coroutinelibargs"); }
@Test
void testCoroutineLibArgs() { runTest("coroutinelibargs"); }
public void testDebugLibArgs() { runTest("debuglibargs"); }
@Test
void testDebugLibArgs() { runTest("debuglibargs"); }
public void testIoLibArgs() { runTest("iolibargs"); }
@Test
void testIoLibArgs() { runTest("iolibargs"); }
public void testMathLibArgs() { runTest("mathlibargs"); }
@Test
void testMathLibArgs() { runTest("mathlibargs"); }
public void testModuleLibArgs() { runTest("modulelibargs"); }
@Test
void testModuleLibArgs() { runTest("modulelibargs"); }
public void testOperators() { runTest("operators"); }
@Test
void testOperators() { runTest("operators"); }
public void testStringLibArgs() { runTest("stringlibargs"); }
@Test
void testStringLibArgs() { runTest("stringlibargs"); }
public void testTableLibArgs() { runTest("tablelibargs"); }
@Test
void testTableLibArgs() { runTest("tablelibargs"); }
}

View File

@@ -0,0 +1,20 @@
package org.luaj;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static org.junit.jupiter.api.Assertions.fail;
import org.luaj.vm2.parser.LuaParser;
public class LuaParserTest extends CompilerTest {
@Override
protected void doTest(String name) {
try {
LuaParser parser = new LuaParser(inputStreamOfLua(name), ISO_8859_1);
parser.Chunk();
} catch (Exception e) {
fail(e.getMessage());
e.printStackTrace();
}
}
}

View File

@@ -19,135 +19,62 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
package org.luaj.vm2;
package org.luaj;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import junit.framework.TestCase;
import org.luaj.vm2.lib.ResourceFinder;
import org.junit.jupiter.api.BeforeEach;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.jme.JmePlatform;
import org.luaj.vm2.lib.jse.JsePlatform;
import org.luaj.vm2.lib.jse.JseProcess;
import org.luaj.vm2.luajc.LuaJC;
abstract public class ScriptDrivenTest extends TestCase implements ResourceFinder {
abstract class PlatformTestCase extends ResourcesTestCase {
public static final boolean nocompile = "true".equals(System.getProperty("nocompile"));
public enum PlatformType {
JME, JSE, LUAJIT,
}
private final PlatformType platform;
private final String subdir;
protected Globals globals;
static final String zipdir = "test/lua/";
static final String zipfile = "luaj3.0-tests.zip";
protected ScriptDrivenTest(PlatformType platform, String subdir) {
this.platform = platform;
this.subdir = subdir;
initGlobals();
}
private PlatformType platform;
private void initGlobals() {
switch (platform) {
default:
case JSE:
case LUAJIT:
globals = org.luaj.vm2.lib.jse.JsePlatform.debugGlobals();
globals = JsePlatform.debugGlobals();
break;
case JME:
globals = org.luaj.vm2.lib.jme.JmePlatform.debugGlobals();
globals = JmePlatform.debugGlobals();
break;
}
}
protected void setUp() throws Exception {
super.setUp();
@BeforeEach
@Override
protected void setUp() {
initGlobals();
globals.finder = this;
}
// ResourceFinder implementation.
public InputStream findResource(String filename) {
InputStream is = findInPlainFile(filename);
if (is != null)
return is;
is = findInPlainFileAsResource("", filename);
if (is != null)
return is;
is = findInPlainFileAsResource("/", filename);
if (is != null)
return is;
is = findInZipFileAsPlainFile(filename);
if (is != null)
return is;
is = findInZipFileAsResource("", filename);
if (is != null)
return is;
is = findInZipFileAsResource("/", filename);
return is;
}
private InputStream findInPlainFileAsResource(String prefix, String filename) {
return getClass().getResourceAsStream(prefix+subdir+filename);
}
private InputStream findInPlainFile(String filename) {
globals.finder = filename -> {
try {
File f = new File(zipdir+subdir+filename);
if (f.exists())
return new FileInputStream(f);
} catch (IOException ioe) {
ioe.printStackTrace();
}
return inputStreamOfFile(filename);
} catch (IOException e) {
return null;
}
private InputStream findInZipFileAsPlainFile(String filename) {
URL zip;
File file = new File(zipdir+zipfile);
try {
if (file.exists()) {
zip = file.toURI().toURL();
String path = "jar:" + zip.toExternalForm() + "!/" + subdir + filename;
URL url = new URL(path);
return url.openStream();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
// Ignore and return null.
} catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
};
}
private InputStream findInZipFileAsResource(String prefix, String filename) {
URL zip = null;
zip = getClass().getResource(zipfile);
if (zip != null)
try {
String path = "jar:" + zip.toExternalForm() + "!/" + subdir + filename;
URL url = new URL(path);
return url.openStream();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
}
protected void setPlatform(PlatformType platform) { this.platform = platform; }
// */
protected void runTest(String testName) {
try {
// override print()
@@ -179,8 +106,8 @@ abstract public class ScriptDrivenTest extends TestCase implements ResourceFinde
}
}
protected LuaValue loadScript(String name, Globals globals) throws IOException {
InputStream script = this.findResource(name + ".lua");
private LuaValue loadScript(String name, Globals globals) throws IOException {
InputStream script = inputStreamOfLua(name);
if (script == null)
fail("Could not load script for test case: " + name);
try {
@@ -205,7 +132,7 @@ abstract public class ScriptDrivenTest extends TestCase implements ResourceFinde
}
private String getExpectedOutput(final String name) throws IOException, InterruptedException {
InputStream output = this.findResource(name + ".out");
InputStream output = inputStreamOfResult(name);
if (output != null)
try {
return readString(output);
@@ -219,7 +146,7 @@ abstract public class ScriptDrivenTest extends TestCase implements ResourceFinde
}
private String executeLuaProcess(String name) throws IOException, InterruptedException {
InputStream script = findResource(name + ".lua");
InputStream script = inputStreamOfLua(name);
if (script == null)
throw new IOException("Failed to find source file " + script);
try {
@@ -233,7 +160,7 @@ abstract public class ScriptDrivenTest extends TestCase implements ResourceFinde
}
}
public static String collectProcessOutput(String[] cmd, final InputStream input)
private static String collectProcessOutput(String[] cmd, final InputStream input)
throws IOException, InterruptedException {
Runtime r = Runtime.getRuntime();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
@@ -241,7 +168,7 @@ abstract public class ScriptDrivenTest extends TestCase implements ResourceFinde
return new String(baos.toByteArray());
}
private String readString(InputStream is) throws IOException {
private static String readString(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
copy(is, baos);
return new String(baos.toByteArray());

View File

@@ -0,0 +1,47 @@
package org.luaj;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Framework to add regression tests as problem areas are found.
*
* To add a new regression test: 1) run "unpack.sh" in the project root 2) add a
* new "lua" file in the "regressions" subdirectory 3) run "repack.sh" in the
* project root 4) add a line to the source file naming the new test
*
* After adding a test, check in the zip file rather than the individual
* regression test files.
*
* @author jrosebor
*/
class RegressionsTest extends CompilingTestCase {
@BeforeEach
@Override
protected void setUp() {
setBaseDir("regressions");
super.setUp();
}
@Test
void testModulo() { doTest("modulo"); }
@Test
void testConstruct() { doTest("construct"); }
@Test
void testBigAttrs() { doTest("bigattr"); }
@Test
void testControlChars() { doTest("controlchars"); }
@Test
void testComparators() { doTest("comparators"); }
@Test
void testMathRandomseed() { doTest("mathrandomseed"); }
@Test
void testVarargs() { doTest("varargs"); }
}

View File

@@ -0,0 +1,38 @@
package org.luaj;
import java.io.IOException;
import java.io.InputStream;
import org.junit.jupiter.api.BeforeEach;
import org.luaj.vm2.Globals;
import org.luaj.vm2.lib.jse.JsePlatform;
abstract class ResourcesTestCase {
private String baseDir;
protected Globals globals;
@BeforeEach
protected void setUp() {
globals = JsePlatform.standardGlobals();
}
protected void setBaseDir(String baseDir) { this.baseDir = baseDir; }
protected InputStream inputStreamOfFile(String file) throws IOException {
return getClass().getClassLoader().getResourceAsStream(baseDir + "/" + file);
}
protected InputStream inputStreamOfLua(String name) throws IOException {
return inputStreamOfFile(name + ".lua");
}
protected InputStream inputStreamOfResult(String name) throws IOException {
return inputStreamOfFile(name + ".out");
}
protected InputStream inputStreamOfBytecode(String name) throws IOException {
return inputStreamOfFile(name + ".lc");
}
}

View File

@@ -1,26 +1,30 @@
package org.luaj.vm2;
package org.luaj.math;
import junit.framework.TestCase;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.LuaError;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.jme.JmePlatform;
import org.luaj.vm2.lib.jse.JsePlatform;
public class MathLibTest extends TestCase {
class MathLibComparisonTest {
private LuaValue j2se;
private LuaValue j2me;
private boolean supportedOnJ2me;
public MathLibTest() {
@BeforeEach
protected void setUp() {
j2se = JsePlatform.standardGlobals().get("math");
j2me = JmePlatform.standardGlobals().get("math");
}
protected void setUp() throws Exception {
supportedOnJ2me = true;
}
public void testMathDPow() {
@Test
void testMathDPow() {
assertEquals(1, j2mepow(2, 0), 0);
assertEquals(2, j2mepow(2, 1), 0);
assertEquals(8, j2mepow(2, 3), 0);
@@ -47,26 +51,30 @@ public class MathLibTest extends TestCase {
return j2me.get("pow").call(LuaValue.valueOf(x), LuaValue.valueOf(y)).todouble();
}
public void testAbs() {
@Test
void testAbs() {
tryMathOp("abs", 23.45);
tryMathOp("abs", -23.45);
}
public void testCos() {
@Test
void testCos() {
tryTrigOps("cos");
}
public void testCosh() {
@Test
void testCosh() {
supportedOnJ2me = false;
tryTrigOps("cosh");
}
public void testDeg() {
@Test
void testDeg() {
tryTrigOps("deg");
}
public void testExp() {
//supportedOnJ2me = false;
@Test
void testExp() {
tryMathOp("exp", 0);
tryMathOp("exp", 0.1);
tryMathOp("exp", .9);
@@ -78,7 +86,8 @@ public class MathLibTest extends TestCase {
tryMathOp("exp", -9);
}
public void testLog() {
@Test
void testLog() {
supportedOnJ2me = false;
tryMathOp("log", 0.1);
tryMathOp("log", .9);
@@ -90,7 +99,8 @@ public class MathLibTest extends TestCase {
tryMathOp("log", -9);
}
public void testRad() {
@Test
void testRad() {
tryMathOp("rad", 0);
tryMathOp("rad", 0.1);
tryMathOp("rad", .9);
@@ -106,16 +116,19 @@ public class MathLibTest extends TestCase {
tryMathOp("rad", -100);
}
public void testSin() {
@Test
void testSin() {
tryTrigOps("sin");
}
public void testSinh() {
@Test
void testSinh() {
supportedOnJ2me = false;
tryTrigOps("sinh");
}
public void testSqrt() {
@Test
void testSqrt() {
tryMathOp("sqrt", 0);
tryMathOp("sqrt", 0.1);
tryMathOp("sqrt", .9);
@@ -125,25 +138,30 @@ public class MathLibTest extends TestCase {
tryMathOp("sqrt", 100);
}
public void testTan() {
@Test
void testTan() {
tryTrigOps("tan");
}
public void testTanh() {
@Test
void testTanh() {
supportedOnJ2me = false;
tryTrigOps("tanh");
}
public void testAtan2() {
@Test
void testAtan2() {
supportedOnJ2me = false;
tryDoubleOps("atan2", false);
}
public void testFmod() {
@Test
void testFmod() {
tryDoubleOps("fmod", false);
}
public void testPow() {
@Test
void testPow() {
tryDoubleOps("pow", true);
}

View File

@@ -1,109 +0,0 @@
/*******************************************************************************
* 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 junit.framework.Test;
import junit.framework.TestSuite;
import org.luaj.vm2.WeakTableTest.WeakKeyTableTest;
import org.luaj.vm2.WeakTableTest.WeakKeyValueTableTest;
import org.luaj.vm2.WeakTableTest.WeakValueTableTest;
import org.luaj.vm2.compiler.CompilerUnitTests;
import org.luaj.vm2.compiler.DumpLoadEndianIntTest;
import org.luaj.vm2.compiler.LuaParserTests;
import org.luaj.vm2.compiler.RegressionTests;
import org.luaj.vm2.compiler.SimpleTests;
import org.luaj.vm2.lib.jse.JsePlatformTest;
import org.luaj.vm2.lib.jse.LuaJavaCoercionTest;
import org.luaj.vm2.lib.jse.LuajavaAccessibleMembersTest;
import org.luaj.vm2.lib.jse.LuajavaClassMembersTest;
import org.luaj.vm2.lib.jse.OsLibTest;
import org.luaj.vm2.script.ScriptEngineTests;
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("All Tests for Luaj-vm2");
// vm tests
TestSuite vm = new TestSuite("VM Tests");
vm.addTestSuite(TypeTest.class);
vm.addTestSuite(UnaryBinaryOperatorsTest.class);
vm.addTestSuite(MetatableTest.class);
vm.addTestSuite(LuaOperationsTest.class);
vm.addTestSuite(StringTest.class);
vm.addTestSuite(OrphanedThreadTest.class);
vm.addTestSuite(VarargsTest.class);
vm.addTestSuite(LoadOrderTest.class);
suite.addTest(vm);
// table tests
TestSuite table = new TestSuite("Table Tests");
table.addTestSuite(TableTest.class);
table.addTestSuite(TableHashTest.class);
table.addTestSuite(WeakValueTableTest.class);
table.addTestSuite(WeakKeyTableTest.class);
table.addTestSuite(WeakKeyValueTableTest.class);
suite.addTest(table);
// bytecode compilers regression tests
TestSuite bytecodetests = FragmentsTest.suite();
suite.addTest(bytecodetests);
// I/O tests
TestSuite io = new TestSuite("I/O Tests");
io.addTestSuite(BufferedStreamTest.class);
io.addTestSuite(UTF8StreamTest.class);
suite.addTest(io);
// prototype compiler
TestSuite compiler = new TestSuite("Lua Compiler Tests");
compiler.addTestSuite(CompilerUnitTests.class);
compiler.addTestSuite(DumpLoadEndianIntTest.class);
compiler.addTestSuite(LuaParserTests.class);
compiler.addTestSuite(RegressionTests.class);
compiler.addTestSuite(SimpleTests.class);
suite.addTest(compiler);
// library tests
TestSuite lib = new TestSuite("Library Tests");
lib.addTestSuite(JsePlatformTest.class);
lib.addTestSuite(LuajavaAccessibleMembersTest.class);
lib.addTestSuite(LuajavaClassMembersTest.class);
lib.addTestSuite(LuaJavaCoercionTest.class);
lib.addTestSuite(RequireClassTest.class);
lib.addTestSuite(OsLibTest.class);
suite.addTest(lib);
// Script engine tests.
TestSuite script = ScriptEngineTests.suite();
suite.addTest(script);
// compatiblity tests
TestSuite compat = CompatibiltyTest.suite();
suite.addTest(compat);
compat.addTestSuite(ErrorsTest.class);
return suite;
}
}

View File

@@ -1,265 +0,0 @@
/*******************************************************************************
* 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 java.lang.ref.WeakReference;
abstract public class WeakTableTest extends TableTest {
public static class MyData {
public final int value;
public MyData(int value) {
this.value = value;
}
public int hashCode() {
return value;
}
public boolean equals(Object o) {
return (o instanceof MyData) && ((MyData) o).value == value;
}
public String toString() {
return "mydata-" + value;
}
}
static void collectGarbage() {
Runtime rt = Runtime.getRuntime();
rt.gc();
try {
Thread.sleep(20);
rt.gc();
Thread.sleep(20);
} catch (Exception e) {
e.printStackTrace();
}
rt.gc();
}
public static class WeakValueTableTest extends WeakTableTest {
protected LuaTable new_Table() { return WeakTable.make(false, true); }
protected LuaTable new_Table(int n, int m) { return WeakTable.make(false, true); }
public void testWeakValuesTable() {
LuaTable t = new_Table();
Object obj = new Object();
LuaTable tableValue = new LuaTable();
LuaString stringValue = LuaString.valueOf("this is a test");
LuaTable tableValue2 = new LuaTable();
t.set("table", tableValue);
t.set("userdata", LuaValue.userdataOf(obj, null));
t.set("string", stringValue);
t.set("string2", LuaValue.valueOf("another string"));
t.set(1, tableValue2);
assertTrue("table must have at least 4 elements", t.getHashLength() >= 4);
assertTrue("array part must have 1 element", t.getArrayLength() >= 1);
// check that table can be used to get elements
assertEquals(tableValue, t.get("table"));
assertEquals(stringValue, t.get("string"));
assertEquals(obj, t.get("userdata").checkuserdata());
assertEquals(tableValue2, t.get(1));
// nothing should be collected, since we have strong references here
collectGarbage();
// check that elements are still there
assertEquals(tableValue, t.get("table"));
assertEquals(stringValue, t.get("string"));
assertEquals(obj, t.get("userdata").checkuserdata());
assertEquals(tableValue2, t.get(1));
// drop our strong references
obj = null;
tableValue = null;
tableValue2 = null;
stringValue = null;
// Garbage collection should cause weak entries to be dropped.
collectGarbage();
// check that they are dropped
assertEquals(LuaValue.NIL, t.get("table"));
assertEquals(LuaValue.NIL, t.get("userdata"));
assertEquals(LuaValue.NIL, t.get(1));
assertFalse("strings should not be in weak references", t.get("string").isnil());
}
}
public static class WeakKeyTableTest extends WeakTableTest {
protected LuaTable new_Table() { return WeakTable.make(true, false); }
protected LuaTable new_Table(int n, int m) { return WeakTable.make(true, false); }
public void testWeakKeysTable() {
LuaTable t = WeakTable.make(true, false);
LuaValue key = LuaValue.userdataOf(new MyData(111));
LuaValue val = LuaValue.userdataOf(new MyData(222));
// set up the table
t.set(key, val);
assertEquals(val, t.get(key));
System.gc();
assertEquals(val, t.get(key));
// drop key and value references, replace them with new ones
WeakReference origkey = new WeakReference(key);
WeakReference origval = new WeakReference(val);
key = LuaValue.userdataOf(new MyData(111));
val = LuaValue.userdataOf(new MyData(222));
// new key and value should be interchangeable (feature of this test class)
assertEquals(key, origkey.get());
assertEquals(val, origval.get());
assertEquals(val, t.get(key));
assertEquals(val, t.get((LuaValue) origkey.get()));
assertEquals(origval.get(), t.get(key));
// value should not be reachable after gc
collectGarbage();
assertEquals(null, origkey.get());
assertEquals(LuaValue.NIL, t.get(key));
collectGarbage();
assertEquals(null, origval.get());
}
public void testNext() {
LuaTable t = WeakTable.make(true, true);
LuaValue key = LuaValue.userdataOf(new MyData(111));
LuaValue val = LuaValue.userdataOf(new MyData(222));
LuaValue key2 = LuaValue.userdataOf(new MyData(333));
LuaValue val2 = LuaValue.userdataOf(new MyData(444));
LuaValue key3 = LuaValue.userdataOf(new MyData(555));
LuaValue val3 = LuaValue.userdataOf(new MyData(666));
// set up the table
t.set(key, val);
t.set(key2, val2);
t.set(key3, val3);
// forget one of the keys
key2 = null;
val2 = null;
collectGarbage();
// table should have 2 entries
int size = 0;
for (LuaValue k = t.next(LuaValue.NIL).arg1(); !k.isnil(); k = t.next(k).arg1()) {
size++;
}
assertEquals(2, size);
}
}
public static class WeakKeyValueTableTest extends WeakTableTest {
protected LuaTable new_Table() { return WeakTable.make(true, true); }
protected LuaTable new_Table(int n, int m) { return WeakTable.make(true, true); }
public void testWeakKeysValuesTable() {
LuaTable t = WeakTable.make(true, true);
LuaValue key = LuaValue.userdataOf(new MyData(111));
LuaValue val = LuaValue.userdataOf(new MyData(222));
LuaValue key2 = LuaValue.userdataOf(new MyData(333));
LuaValue val2 = LuaValue.userdataOf(new MyData(444));
LuaValue key3 = LuaValue.userdataOf(new MyData(555));
LuaValue val3 = LuaValue.userdataOf(new MyData(666));
// set up the table
t.set(key, val);
t.set(key2, val2);
t.set(key3, val3);
assertEquals(val, t.get(key));
assertEquals(val2, t.get(key2));
assertEquals(val3, t.get(key3));
System.gc();
assertEquals(val, t.get(key));
assertEquals(val2, t.get(key2));
assertEquals(val3, t.get(key3));
// drop key and value references, replace them with new ones
WeakReference origkey = new WeakReference(key);
WeakReference origval = new WeakReference(val);
WeakReference origkey2 = new WeakReference(key2);
WeakReference origval2 = new WeakReference(val2);
WeakReference origkey3 = new WeakReference(key3);
WeakReference origval3 = new WeakReference(val3);
key = LuaValue.userdataOf(new MyData(111));
val = LuaValue.userdataOf(new MyData(222));
key2 = LuaValue.userdataOf(new MyData(333));
// don't drop val2, or key3
val3 = LuaValue.userdataOf(new MyData(666));
// no values should be reachable after gc
collectGarbage();
assertEquals(null, origkey.get());
assertEquals(null, origval.get());
assertEquals(null, origkey2.get());
assertEquals(null, origval3.get());
assertEquals(LuaValue.NIL, t.get(key));
assertEquals(LuaValue.NIL, t.get(key2));
assertEquals(LuaValue.NIL, t.get(key3));
// all originals should be gone after gc, then access
val2 = null;
key3 = null;
collectGarbage();
assertEquals(null, origval2.get());
assertEquals(null, origkey3.get());
}
public void testReplace() {
LuaTable t = WeakTable.make(true, true);
LuaValue key = LuaValue.userdataOf(new MyData(111));
LuaValue val = LuaValue.userdataOf(new MyData(222));
LuaValue key2 = LuaValue.userdataOf(new MyData(333));
LuaValue val2 = LuaValue.userdataOf(new MyData(444));
LuaValue key3 = LuaValue.userdataOf(new MyData(555));
LuaValue val3 = LuaValue.userdataOf(new MyData(666));
// set up the table
t.set(key, val);
t.set(key2, val2);
t.set(key3, val3);
LuaValue val4 = LuaValue.userdataOf(new MyData(777));
t.set(key2, val4);
// table should have 3 entries
int size = 0;
for (LuaValue k = t.next(LuaValue.NIL).arg1(); !k.isnil() && size < 1000; k = t.next(k).arg1()) {
size++;
}
assertEquals(3, size);
}
}
}

View File

@@ -1,122 +0,0 @@
package org.luaj.vm2.compiler;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import junit.framework.TestCase;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LoadState;
import org.luaj.vm2.Print;
import org.luaj.vm2.Prototype;
import org.luaj.vm2.lib.jse.JsePlatform;
abstract public class AbstractUnitTests extends TestCase {
private final String dir;
private final String jar;
private Globals globals;
public AbstractUnitTests(String zipdir, String zipfile, String dir) {
URL zip = null;
zip = getClass().getResource(zipfile);
if (zip == null) {
File file = new File(zipdir + "/" + zipfile);
try {
if (file.exists())
zip = file.toURI().toURL();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
if (zip == null)
throw new RuntimeException("not found: " + zipfile);
this.jar = "jar:" + zip.toExternalForm() + "!/";
this.dir = dir;
}
protected void setUp() throws Exception {
super.setUp();
globals = JsePlatform.standardGlobals();
}
protected String pathOfFile(String file) {
return jar + dir + "/" + file;
}
protected InputStream inputStreamOfPath(String path) throws IOException {
URL url = new URL(path);
return url.openStream();
}
protected InputStream inputStreamOfFile(String file) throws IOException {
return inputStreamOfPath(pathOfFile(file));
}
protected void doTest(String file) {
try {
// load source from jar
String path = pathOfFile(file);
byte[] lua = bytesFromJar(path);
// compile in memory
InputStream is = new ByteArrayInputStream(lua);
Prototype p = globals.loadPrototype(is, "@" + file, "bt");
String actual = protoToString(p);
// load expected value from jar
byte[] luac = bytesFromJar(path.substring(0, path.length()-4) + ".lc");
Prototype e = loadFromBytes(luac, file);
String expected = protoToString(e);
// compare results
assertEquals(expected, actual);
// dump into memory
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DumpState.dump(p, baos, false);
byte[] dumped = baos.toByteArray();
// re-undump
Prototype p2 = loadFromBytes(dumped, file);
String actual2 = protoToString(p2);
// compare again
assertEquals(actual, actual2);
} catch (IOException e) {
fail(e.toString());
}
}
protected byte[] bytesFromJar(String path) throws IOException {
InputStream is = inputStreamOfPath(path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int n;
while ( (n = is.read(buffer)) >= 0 )
baos.write(buffer, 0, n);
is.close();
return baos.toByteArray();
}
protected Prototype loadFromBytes(byte[] bytes, String script) throws IOException {
InputStream is = new ByteArrayInputStream(bytes);
return globals.loadPrototype(is, script, "b");
}
protected String protoToString(Prototype p) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
Print.ps = ps;
new Print().printFunction(p, true);
return baos.toString();
}
}

View File

@@ -1,62 +0,0 @@
package org.luaj.vm2.compiler;
public class CompilerUnitTests extends AbstractUnitTests {
public CompilerUnitTests() {
super("test/lua", "luaj3.0-tests.zip", "lua5.2.1-tests");
}
public void testAll() { doTest("all.lua"); }
public void testApi() { doTest("api.lua"); }
public void testAttrib() { doTest("attrib.lua"); }
public void testBig() { doTest("big.lua"); }
public void testBitwise() { doTest("bitwise.lua"); }
public void testCalls() { doTest("calls.lua"); }
public void testChecktable() { doTest("checktable.lua"); }
public void testClosure() { doTest("closure.lua"); }
public void testCode() { doTest("code.lua"); }
public void testConstruct() { doTest("constructs.lua"); }
public void testCoroutine() { doTest("coroutine.lua"); }
public void testDb() { doTest("db.lua"); }
public void testErrors() { doTest("errors.lua"); }
public void testEvents() { doTest("events.lua"); }
public void testFiles() { doTest("files.lua"); }
public void testGc() { doTest("gc.lua"); }
public void testGoto() { doTest("goto.lua"); }
public void testLiterals() { doTest("literals.lua"); }
public void testLocals() { doTest("locals.lua"); }
public void testMain() { doTest("main.lua"); }
public void testMath() { doTest("math.lua"); }
public void testNextvar() { doTest("nextvar.lua"); }
public void testPm() { doTest("pm.lua"); }
public void testSort() { doTest("sort.lua"); }
public void testStrings() { doTest("strings.lua"); }
public void testVararg() { doTest("vararg.lua"); }
public void testVerybig() { doTest("verybig.lua"); }
}

View File

@@ -1,28 +0,0 @@
package org.luaj.vm2.compiler;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.parser.LuaParser;
public class LuaParserTests extends CompilerUnitTests {
protected void setUp() throws Exception {
super.setUp();
LuaValue.valueOf(true);
}
protected void doTest(String file) {
try {
InputStream is = inputStreamOfFile(file);
Reader r = new InputStreamReader(is, "ISO-8859-1");
LuaParser parser = new LuaParser(r);
parser.Chunk();
} catch (Exception e) {
fail(e.getMessage());
e.printStackTrace();
}
}
}

View File

@@ -1,34 +0,0 @@
package org.luaj.vm2.compiler;
/**
* Framework to add regression tests as problem areas are found.
*
* To add a new regression test: 1) run "unpack.sh" in the project root 2) add a
* new "lua" file in the "regressions" subdirectory 3) run "repack.sh" in the
* project root 4) add a line to the source file naming the new test
*
* After adding a test, check in the zip file rather than the individual
* regression test files.
*
* @author jrosebor
*/
public class RegressionTests extends AbstractUnitTests {
public RegressionTests() {
super("test/lua", "luaj3.0-tests.zip", "regressions");
}
public void testModulo() { doTest("modulo.lua"); }
public void testConstruct() { doTest("construct.lua"); }
public void testBigAttrs() { doTest("bigattr.lua"); }
public void testControlChars() { doTest("controlchars.lua"); }
public void testComparators() { doTest("comparators.lua"); }
public void testMathRandomseed() { doTest("mathrandomseed.lua"); }
public void testVarargs() { doTest("varargs.lua"); }
}

View File

@@ -1,110 +0,0 @@
package org.luaj.vm2.lib.jse;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.OsLib;
import org.luaj.vm2.lib.jme.JmePlatform;
import junit.framework.TestCase;
public class OsLibTest extends TestCase {
LuaValue jme_lib;
LuaValue jse_lib;
double time;
public void setUp() {
jse_lib = JsePlatform.standardGlobals().get("os");
;
jme_lib = JmePlatform.standardGlobals().get("os");
;
time = new java.util.Date(2001-1900, 7, 23, 14, 55, 02).getTime()/1000.0;
}
void t(String format, String expected) {
String actual = jme_lib.get("date").call(LuaValue.valueOf(format), LuaValue.valueOf(time)).tojstring();
assertEquals(expected, actual);
}
public void testStringDateChars() { t("foo", "foo"); }
public void testStringDate_a() { t("%a", "Thu"); }
public void testStringDate_A() { t("%A", "Thursday"); }
public void testStringDate_b() { t("%b", "Aug"); }
public void testStringDate_B() { t("%B", "August"); }
public void testStringDate_c() { t("%c", "Thu Aug 23 14:55:02 2001"); }
public void testStringDate_d() { t("%d", "23"); }
public void testStringDate_H() { t("%H", "14"); }
public void testStringDate_I() { t("%I", "02"); }
public void testStringDate_j() { t("%j", "235"); }
public void testStringDate_m() { t("%m", "08"); }
public void testStringDate_M() { t("%M", "55"); }
public void testStringDate_p() { t("%p", "PM"); }
public void testStringDate_S() { t("%S", "02"); }
public void testStringDate_U() { t("%U", "33"); }
public void testStringDate_w() { t("%w", "4"); }
public void testStringDate_W() { t("%W", "34"); }
public void testStringDate_x() { t("%x", "08/23/01"); }
public void testStringDate_X() { t("%X", "14:55:02"); }
public void testStringDate_y() { t("%y", "01"); }
public void testStringDate_Y() { t("%Y", "2001"); }
public void testStringDate_Pct() { t("%%", "%"); }
static final double DAY = 24.*3600.;
public void testStringDate_UW_neg4() { time -= 4*DAY; t("%c %U %W", "Sun Aug 19 14:55:02 2001 33 33"); }
public void testStringDate_UW_neg3() { time -= 3*DAY; t("%c %U %W", "Mon Aug 20 14:55:02 2001 33 34"); }
public void testStringDate_UW_neg2() { time -= 2*DAY; t("%c %U %W", "Tue Aug 21 14:55:02 2001 33 34"); }
public void testStringDate_UW_neg1() { time -= DAY; t("%c %U %W", "Wed Aug 22 14:55:02 2001 33 34"); }
public void testStringDate_UW_pos0() { time += 0; t("%c %U %W", "Thu Aug 23 14:55:02 2001 33 34"); }
public void testStringDate_UW_pos1() { time += DAY; t("%c %U %W", "Fri Aug 24 14:55:02 2001 33 34"); }
public void testStringDate_UW_pos2() { time += 2*DAY; t("%c %U %W", "Sat Aug 25 14:55:02 2001 33 34"); }
public void testStringDate_UW_pos3() { time += 3*DAY; t("%c %U %W", "Sun Aug 26 14:55:02 2001 34 34"); }
public void testStringDate_UW_pos4() { time += 4*DAY; t("%c %U %W", "Mon Aug 27 14:55:02 2001 34 35"); }
public void testJseOsGetenvForEnvVariables() {
LuaValue USER = LuaValue.valueOf("USER");
LuaValue jse_user = jse_lib.get("getenv").call(USER);
LuaValue jme_user = jme_lib.get("getenv").call(USER);
assertFalse(jse_user.isnil());
assertTrue(jme_user.isnil());
System.out.println("User: " + jse_user);
}
public void testJseOsGetenvForSystemProperties() {
System.setProperty("test.key.foo", "test.value.bar");
LuaValue key = LuaValue.valueOf("test.key.foo");
LuaValue value = LuaValue.valueOf("test.value.bar");
LuaValue jse_value = jse_lib.get("getenv").call(key);
LuaValue jme_value = jme_lib.get("getenv").call(key);
assertEquals(value, jse_value);
assertEquals(value, jme_value);
}
}

View File

@@ -1,334 +0,0 @@
/*******************************************************************************
* Copyright (c) 2013 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.script;
import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.Reader;
import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.SimpleBindings;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.luaj.vm2.LuaFunction;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.OneArgFunction;
public class ScriptEngineTests extends TestSuite {
public static TestSuite suite() {
TestSuite suite = new TestSuite("Script Engine Tests");
suite.addTest(new TestSuite(LookupEngineTestCase.class, "Lookup Engine"));
suite.addTest(new TestSuite(DefaultBindingsTest.class, "Default Bindings"));
suite.addTest(new TestSuite(SimpleBindingsTest.class, "Simple Bindings"));
suite.addTest(new TestSuite(CompileClosureTest.class, "Compile Closure"));
suite.addTest(new TestSuite(CompileNonClosureTest.class, "Compile NonClosure"));
suite.addTest(new TestSuite(UserContextTest.class, "User Context"));
suite.addTest(new TestSuite(WriterTest.class, "Writer"));
return suite;
}
public static class LookupEngineTestCase extends TestCase {
public void testGetEngineByExtension() {
ScriptEngine e = new ScriptEngineManager().getEngineByExtension(".lua");
assertNotNull(e);
assertEquals(LuaScriptEngine.class, e.getClass());
}
public void testGetEngineByName() {
ScriptEngine e = new ScriptEngineManager().getEngineByName("luaj");
assertNotNull(e);
assertEquals(LuaScriptEngine.class, e.getClass());
}
public void testGetEngineByMimeType() {
ScriptEngine e = new ScriptEngineManager().getEngineByMimeType("text/lua");
assertNotNull(e);
assertEquals(LuaScriptEngine.class, e.getClass());
}
public void testFactoryMetadata() {
ScriptEngine e = new ScriptEngineManager().getEngineByName("luaj");
ScriptEngineFactory f = e.getFactory();
assertEquals("Luaj", f.getEngineName());
assertEquals("Luaj 0.0", f.getEngineVersion());
assertEquals("lua", f.getLanguageName());
assertEquals("5.2", f.getLanguageVersion());
}
}
public static class DefaultBindingsTest extends EngineTestCase {
protected Bindings createBindings() {
return e.createBindings();
}
}
public static class SimpleBindingsTest extends EngineTestCase {
protected Bindings createBindings() {
return new SimpleBindings();
}
}
public static class CompileClosureTest extends DefaultBindingsTest {
protected void setUp() throws Exception {
System.setProperty("org.luaj.luajc", "false");
super.setUp();
}
public void testCompiledFunctionIsClosure() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("return 'foo'");
LuaValue value = ((LuaScriptEngine.LuajCompiledScript) cs).function;
assertTrue(value.isclosure());
}
}
public static class CompileNonClosureTest extends DefaultBindingsTest {
protected void setUp() throws Exception {
System.setProperty("org.luaj.luajc", "true");
super.setUp();
}
public void testCompiledFunctionIsNotClosure() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("return 'foo'");
LuaValue value = ((LuaScriptEngine.LuajCompiledScript) cs).function;
assertFalse(value.isclosure());
}
}
abstract public static class EngineTestCase extends TestCase {
protected ScriptEngine e;
protected Bindings b;
abstract protected Bindings createBindings();
protected void setUp() throws Exception {
this.e = new ScriptEngineManager().getEngineByName("luaj");
this.b = createBindings();
}
public void testSqrtIntResult() throws ScriptException {
e.put("x", 25);
e.eval("y = math.sqrt(x)");
Object y = e.get("y");
assertEquals(5, y);
}
public void testOneArgFunction() throws ScriptException {
e.put("x", 25);
e.eval("y = math.sqrt(x)");
Object y = e.get("y");
assertEquals(5, y);
e.put("f", new OneArgFunction() {
public LuaValue call(LuaValue arg) {
return LuaValue.valueOf(arg.toString() + "123");
}
});
Object r = e.eval("return f('abc')");
assertEquals("abc123", r);
}
public void testCompiledScript() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("y = math.sqrt(x); return y");
b.put("x", 144);
assertEquals(12, cs.eval(b));
}
public void testBuggyLuaScript() {
try {
e.eval("\n\nbuggy lua code\n\n");
} catch (ScriptException se) {
assertEquals("eval threw javax.script.ScriptException: [string \"script\"]:3: syntax error",
se.getMessage());
return;
}
fail("buggy script did not throw ScriptException as expected.");
}
public void testScriptRedirection() throws ScriptException {
Reader input = new CharArrayReader("abcdefg\nhijk".toCharArray());
CharArrayWriter output = new CharArrayWriter();
CharArrayWriter errors = new CharArrayWriter();
String script = "print(\"string written using 'print'\")\n"
+ "io.write(\"string written using 'io.write()'\\n\")\n"
+ "io.stdout:write(\"string written using 'io.stdout:write()'\\n\")\n"
+ "io.stderr:write(\"string written using 'io.stderr:write()'\\n\")\n"
+ "io.write([[string read using 'io.stdin:read(\"*l\")':]]..io.stdin:read(\"*l\")..\"\\n\")\n";
// Evaluate script with redirection set
e.getContext().setReader(input);
e.getContext().setWriter(output);
e.getContext().setErrorWriter(errors);
e.eval(script);
final String expectedOutput = "string written using 'print'\n" + "string written using 'io.write()'\n"
+ "string written using 'io.stdout:write()'\n" + "string read using 'io.stdin:read(\"*l\")':abcdefg\n";
assertEquals(expectedOutput, output.toString());
final String expectedErrors = "string written using 'io.stderr:write()'\n";
assertEquals(expectedErrors, errors.toString());
// Evaluate script with redirection reset
output.reset();
errors.reset();
// e.getContext().setReader(null); // This will block if using actual STDIN
e.getContext().setWriter(null);
e.getContext().setErrorWriter(null);
e.eval(script);
assertEquals("", output.toString());
assertEquals("", errors.toString());
}
public void testBindingJavaInt() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("y = x; return 'x '..type(x)..' '..tostring(x)\n");
b.put("x", 111);
assertEquals("x number 111", cs.eval(b));
assertEquals(111, b.get("y"));
}
public void testBindingJavaDouble() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("y = x; return 'x '..type(x)..' '..tostring(x)\n");
b.put("x", 125.125);
assertEquals("x number 125.125", cs.eval(b));
assertEquals(125.125, b.get("y"));
}
public void testBindingJavaString() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("y = x; return 'x '..type(x)..' '..tostring(x)\n");
b.put("x", "foo");
assertEquals("x string foo", cs.eval(b));
assertEquals("foo", b.get("y"));
}
public void testBindingJavaObject() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("y = x; return 'x '..type(x)..' '..tostring(x)\n");
b.put("x", new SomeUserClass());
assertEquals("x userdata some-user-value", cs.eval(b));
assertEquals(SomeUserClass.class, b.get("y").getClass());
}
public void testBindingJavaArray() throws ScriptException {
CompiledScript cs = ((Compilable) e)
.compile("y = x; return 'x '..type(x)..' '..#x..' '..x[1]..' '..x[2]\n");
b.put("x", new int[] { 777, 888 });
assertEquals("x userdata 2 777 888", cs.eval(b));
assertEquals(int[].class, b.get("y").getClass());
}
public void testBindingLuaFunction() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("y = function(x) return 678 + x end; return 'foo'");
assertEquals("foo", cs.eval(b).toString());
assertTrue(b.get("y") instanceof LuaFunction);
assertEquals(LuaValue.valueOf(801), ((LuaFunction) b.get("y")).call(LuaValue.valueOf(123)));
}
public void testUserClasses() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("x = x or luajava.newInstance('java.lang.String', 'test')\n"
+ "return 'x ' .. type(x) .. ' ' .. tostring(x)\n");
assertEquals("x string test", cs.eval(b));
b.put("x", new SomeUserClass());
assertEquals("x userdata some-user-value", cs.eval(b));
}
public void testReturnMultipleValues() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("return 'foo', 'bar'\n");
Object o = cs.eval();
assertEquals(Object[].class, o.getClass());
Object[] array = (Object[]) o;
assertEquals(2, array.length);
assertEquals("foo", array[0]);
assertEquals("bar", array[1]);
}
}
public static class SomeUserClass {
public String toString() {
return "some-user-value";
}
}
public static class UserContextTest extends TestCase {
protected ScriptEngine e;
protected Bindings b;
protected ScriptContext c;
public void setUp() {
this.e = new ScriptEngineManager().getEngineByName("luaj");
this.c = new LuajContext();
this.b = c.getBindings(ScriptContext.ENGINE_SCOPE);
}
public void testUncompiledScript() throws ScriptException {
b.put("x", 144);
assertEquals(12, e.eval("z = math.sqrt(x); return z", b));
assertEquals(12, b.get("z"));
assertEquals(null, e.getBindings(ScriptContext.ENGINE_SCOPE).get("z"));
assertEquals(null, e.getBindings(ScriptContext.GLOBAL_SCOPE).get("z"));
b.put("x", 25);
assertEquals(5, e.eval("z = math.sqrt(x); return z", c));
assertEquals(5, b.get("z"));
assertEquals(null, e.getBindings(ScriptContext.ENGINE_SCOPE).get("z"));
assertEquals(null, e.getBindings(ScriptContext.GLOBAL_SCOPE).get("z"));
}
public void testCompiledScript() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("z = math.sqrt(x); return z");
b.put("x", 144);
assertEquals(12, cs.eval(b));
assertEquals(12, b.get("z"));
b.put("x", 25);
assertEquals(5, cs.eval(c));
assertEquals(5, b.get("z"));
}
}
public static class WriterTest extends TestCase {
protected ScriptEngine e;
protected Bindings b;
public void setUp() {
this.e = new ScriptEngineManager().getEngineByName("luaj");
this.b = e.getBindings(ScriptContext.ENGINE_SCOPE);
}
public void testWriter() throws ScriptException {
CharArrayWriter output = new CharArrayWriter();
CharArrayWriter errors = new CharArrayWriter();
e.getContext().setWriter(output);
e.getContext().setErrorWriter(errors);
e.eval("io.write( [[line]] )");
assertEquals("line", output.toString());
e.eval("io.write( [[ one\nline two\n]] )");
assertEquals("line one\nline two\n", output.toString());
output.reset();
}
}
}

11
pom.xml
View File

@@ -69,9 +69,9 @@
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.7.2</version>
<scope>test</scope>
</dependency>
</dependencies>
@@ -90,6 +90,11 @@
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.2.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>