Add unit tests used in vm1

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

View File

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

View File

@@ -1,203 +0,0 @@
-- utilities to check that args of various types pass or fail
-- argument type checking
local ok = '-\t'
local fail = 'fail '
local needcheck = 'needcheck '
local badmsg = 'badmsg '
akey = 'aa'
astring = 'abc'
astrnum = '789'
anumber = 1.23
ainteger = 345
adouble = 123.456
aboolean = true
atable = {[akey]=456}
afunction = function() end
anil = nil
athread = coroutine.create(afunction)
anylua = { nil, astring, anumber, aboolean, atable, afunction, athread }
somestring = { astring, anumber }
somenumber = { anumber, astrnum }
someboolean = { aboolean }
sometable = { atable }
somefunction = { afunction }
somenil = { anil }
somekey = { akey }
notakey = { astring, anumber, aboolean, atable, afunction }
notastring = { nil, aboolean, atable, afunction, athread }
notanumber = { nil, astring, aboolean, atable, afunction, athread }
notaboolean = { nil, astring, anumber, atable, afunction, athread }
notatable = { nil, astring, anumber, aboolean, afunction, athread }
notafunction = { nil, astring, anumber, aboolean, atable, athread }
notathread = { nil, astring, anumber, aboolean, atable, afunction }
notanil = { astring, anumber, aboolean, atable, afunction, athread }
nonstring = { aboolean, atable, afunction, athread }
nonnumber = { astring, aboolean, atable, afunction, athread }
nonboolean = { astring, anumber, atable, afunction, athread }
nontable = { astring, anumber, aboolean, afunction, athread }
nonfunction = { astring, anumber, aboolean, atable, athread }
nonthread = { astring, anumber, aboolean, atable, afunction }
nonkey = { astring, anumber, aboolean, atable, afunction }
local structtypes = {
['table']='<table>',
['function']='<function>',
['thread']='<thread>',
['userdata']='<userdata>',
}
local function bracket(v)
return "<"..type(v)..">"
end
local function quote(v)
return "'"..v.."'"
end
local function ellipses(v)
local s = tostring(v)
return #s <= 8 and s or (string.sub(s,1,8)..'...')
end
local pretty = {
['table']=bracket,
['function']=bracket,
['thread']=bracket,
['userdata']=bracket,
['string']= quote,
['number']= ellipses,
}
local function values(list)
local t = {}
for i=1,#list do
local ai = list[i]
local fi = pretty[type(ai)]
t[i] = fi and fi(ai) or tostring(ai)
end
return table.concat(t,',')
end
local function types(list)
local t = {}
for i=1,#list do
local ai = list[i]
t[i] = type(ai)
end
return table.concat(t,',')
end
local function signature(name,arglist)
return name..'('..values(arglist)..')'
end
local function dup(t)
local s = {}
for i=1,#t do
s[i] = t[i]
end
return s
end
local function split(t)
local s = {}
local n = #t
for i=1,n-1 do
s[i] = t[i]
end
return s,t[n]
end
local function expand(argsets, typesets, ...)
local n = typesets and #typesets or 0
if n <= 0 then
table.insert(argsets,{...})
return argsets
end
local s,v = split(typesets)
for i=1,#v do
expand(argsets, s, v[i], ...)
end
return argsets
end
local function arglists(typesets)
local argsets = expand({},typesets)
return ipairs(argsets)
end
local function lookup( name )
return loadstring('return '..name)()
end
local function invoke( name, arglist )
local s,c = pcall(lookup, name)
if not s then return s,c end
local f = function(...)
local u = unpack
local t = { c(...) }
return u(t)
end
return pcall(f, unpack(arglist))
end
-- messages, banners
local _print = print
local _tostring = tostring
local _find = string.find
function banner(name)
_print( '====== '.._tostring(name)..' ======' )
end
local function subbanner(name)
_print( '--- '.._tostring(name) )
end
local function pack(s,...)
return s,{...}
end
-- check that all combinations of arguments pass
function checkallpass( name, typesets, typesonly )
subbanner('checkallpass')
for i,v in arglists(typesets) do
local sig = signature(name,v)
local s,r = pack( invoke( name, v ) )
if s then
if typesonly then
_print( ok, sig, types(r) )
else
_print( ok, sig, values(r) )
end
else
_print( fail, sig, values(r) )
end
end
end
-- check that all combinations of arguments fail in some way,
-- ignore error messages
function checkallerrors( name, typesets, template )
subbanner('checkallerrors')
template = _tostring(template)
for i,v in arglists(typesets) do
local sig = signature(name,v)
local s,e = invoke( name, v )
if not s then
if _find(e, template, 1, true) then
_print( ok, sig, '...'..template..'...' )
else
_print( badmsg, sig, "template='"..template.."' actual='"..e.."'" )
end
else
_print( needcheck, sig, e )
end
end
end

View File

@@ -1,171 +0,0 @@
package.path = "?.lua;src/test/errors/?.lua"
require 'args'
-- arg types for basic library functions
-- assert
banner('assert')
checkallpass('assert',{{true,123},anylua})
checkallerrors('assert',{{nil,false},{nil}},'assertion failed')
checkallerrors('assert',{{nil,false},{'message'}},'message')
-- collectgarbage
banner('collectgarbage')
checkallpass('collectgarbage',{{'collect','count'}},true)
checkallerrors('collectgarbage',{notanil},'bad argument #1')
-- dofile
banner('dofile')
checkallpass('dofile', {})
checkallpass('dofile', {{'src/test/errors/args.lua'}})
checkallerrors('dofile', {{'args.lua'}}, 'cannot open args.lua')
checkallerrors('dofile', {nonstring}, 'bad argument #1')
-- error
banner('error')
checkallerrors('error', {{'message'},{nil,0,1,2}}, 'message')
checkallerrors('error', {{123},{nil,1,2}}, 123)
-- getfenv
banner('getfenv')
checkallpass('getfenv', {{nil,print,function()end,0,1,2}})
checkallerrors('getfenv', {{true,{},'abc'}}, 'bad argument #1')
-- getmetatable
banner('getmetatable')
checkallpass('getmetatable', {notanil})
checkallerrors('getmetatable',{},'bad argument #1')
-- ipairs
banner('ipairs')
checkallpass('ipairs', {sometable})
checkallerrors('ipairs', {notatable}, 'bad argument #1')
-- load
banner('load')
checkallpass('load', {somefunction,{nil,astring}})
checkallerrors('load', {notafunction,{nil,astring,anumber}}, 'bad argument #1')
checkallerrors('load', {somefunction,{afunction,atable}}, 'bad argument #2')
-- loadfile
banner('loadfile')
checkallpass('loadfile', {})
checkallpass('loadfile', {{'bogus'}})
checkallpass('loadfile', {{'src/test/errors/args.lua'}})
checkallpass('loadfile', {{'args.lua'}})
checkallerrors('loadfile', {nonstring}, 'bad argument #1')
-- loadstring
banner('loadstring')
checkallpass('loadstring', {{'return'}})
checkallpass('loadstring', {{'return'},{'mychunk'}})
checkallpass('loadstring', {{'return a ... b'},{'mychunk'}},true)
checkallerrors('loadstring', {{'return a ... b'},{'mychunk'}},'hello')
checkallerrors('loadstring', {notastring,{nil,astring,anumber}}, 'bad argument #1')
checkallerrors('loadstring', {{'return'},{afunction,atable}}, 'bad argument #2')
-- next
banner('next')
checkallpass('next', {sometable,somekey})
checkallerrors('next', {notatable,{nil,1}}, 'bad argument #1')
checkallerrors('next', {sometable,nonkey}, 'invalid key')
-- pairs
banner('pairs')
checkallpass('pairs', {sometable})
checkallerrors('pairs', {notatable}, 'bad argument #1')
-- pcall
banner('pcall')
checkallpass('pcall', {notanil,anylua}, true)
checkallerrors('pcall',{},'bad argument #1')
-- print
banner('print')
checkallpass('print', {})
checkallpass('print', {{nil,astring,anumber,aboolean}})
-- rawequal
banner('rawequal')
checkallpass('rawequal', {notanil,notanil})
checkallerrors('rawequal', {}, 'bad argument #1')
checkallerrors('rawequal', {notanil}, 'bad argument #2')
-- rawget
banner('rawget')
checkallpass('rawget', {sometable,somekey})
checkallpass('rawget', {sometable,nonkey})
checkallerrors('rawget', {sometable,somenil},'bad argument #2')
checkallerrors('rawget', {notatable,notakey}, 'bad argument #1')
checkallerrors('rawget', {}, 'bad argument #1')
-- rawset
banner('rawset')
checkallpass('rawset', {sometable,somekey,notanil})
checkallpass('rawset', {sometable,nonkey,notanil})
checkallerrors('rawset', {sometable,somenil},'table index is nil')
checkallerrors('rawset', {}, 'bad argument #1')
checkallerrors('rawset', {notatable,somestring,somestring}, 'bad argument #1')
checkallerrors('rawset', {sometable,somekey}, 'bad argument #3')
-- select
banner('select')
checkallpass('select', {{anumber,'#'},anylua})
checkallerrors('select', {notanumber}, 'bad argument #1')
-- setfenv
banner('setfenv')
local g = _G
checkallpass('setfenv', {{function()end},sometable})
checkallerrors('setfenv', {{-1, '-2'},{g}}, 'level must be non-negative')
checkallerrors('setfenv', {{10, '11'},{g}}, 'invalid level')
checkallerrors('setfenv', {{rawset},{g}}, 'cannot change environment of given object')
checkallerrors('setfenv', {{atable,athread,aboolean,astring},{g}}, 'bad argument #1')
checkallerrors('setfenv', {notafunction}, 'bad argument #2')
checkallerrors('setfenv', {anylua}, 'bad argument #2')
checkallerrors('setfenv', {{function()end},notatable}, 'bad argument #2')
-- setmetatable
banner('setmetatable')
checkallpass('setmetatable', {sometable,sometable})
checkallpass('setmetatable', {sometable,{}})
checkallerrors('setmetatable',{notatable,sometable},'bad argument #1')
checkallerrors('setmetatable',{sometable,notatable},'bad argument #2')
-- tonumber
banner('tonumber')
checkallpass('tonumber',{somenumber,{nil,2,10,36}})
checkallpass('tonumber',{notanil,{nil,10}})
checkallerrors('tonumber',{{nil,afunction,atable},{2,9,11,36}},'bad argument #1')
checkallerrors('tonumber',{somenumber,{1,37,atable,afunction,aboolean}},'bad argument #2')
-- tostring
banner('tostring')
checkallpass('tostring',{{astring,anumber,aboolean}})
checkallpass('tostring',{{atable,afunction,athread}},true)
checkallpass('tostring',{{astring,anumber,aboolean},{'anchor'}})
checkallpass('tostring',{{atable,afunction,athread},{'anchor'}},true)
checkallerrors('tostring',{},'bad argument #1')
-- type
banner('type')
checkallpass('type',{notanil})
checkallpass('type',{anylua,{'anchor'}})
checkallerrors('type',{},'bad argument')
-- unpack
banner('unpack')
checkallpass('unpack',{sometable})
checkallpass('unpack',{sometable,somenumber})
checkallpass('unpack',{sometable,somenumber,somenumber})
checkallerrors('unpack',{notatable,somenumber,somenumber},'bad argument #1')
checkallerrors('unpack',{sometable,nonnumber,somenumber},'bad argument #2')
checkallerrors('unpack',{sometable,somenumber,nonnumber},'bad argument #3')
-- xpcall
banner('xpcall')
checkallpass('xpcall', {notanil,nonfunction})
checkallpass('xpcall', {notanil,{function(...)return 'aaa', 'bbb', #{...} end}})
checkallerrors('xpcall',{anylua},'bad argument #2')

View File

@@ -1,47 +0,0 @@
package.path = "?.lua;src/test/errors/?.lua"
require 'args'
-- arg type tests for coroutine library functions
-- coroutine.create
banner('coroutine.create')
checkallpass('coroutine.create',{somefunction})
checkallerrors('coroutine.create',{notafunction},'bad argument')
-- coroutine.resume
banner('coroutine.resume')
local co = coroutine.create(function() while true do coroutine.yield() end end)
checkallpass('coroutine.resume',{{co},anylua})
checkallerrors('coroutine.resume',{notathread},'bad argument #1')
-- coroutine.running
banner('coroutine.running')
checkallpass('coroutine.running',{anylua})
-- coroutine.status
banner('coroutine.status')
checkallpass('coroutine.status',{{co}})
checkallerrors('coroutine.status',{notathread},'bad argument #1')
-- coroutine.wrap
banner('coroutine.wrap')
checkallpass('coroutine.wrap',{somefunction})
checkallerrors('coroutine.wrap',{notafunction},'bad argument #1')
-- coroutine.yield
banner('coroutine.yield')
local function f()
print( 'yield', coroutine.yield() )
print( 'yield', coroutine.yield(astring,anumber,aboolean) )
error('error within coroutine thread')
end
local co = coroutine.create( f )
print( 'status', coroutine.status(co) )
print( coroutine.resume(co,astring,anumber) )
print( 'status', coroutine.status(co) )
print( coroutine.resume(co,astring,anumber) )
print( 'status', coroutine.status(co) )
local s,e = coroutine.resume(co,astring,anumber)
print( s, string.match(e,'error within coroutine thread') or 'bad message: '..tostring(e) )
print( 'status', coroutine.status(co) )

View File

@@ -1,76 +0,0 @@
package.path = "?.lua;src/test/errors/?.lua"
require 'args'
-- arg type tests for io library functions
local f
-- io.close ([file])
banner('io.close')
f = io.open("abc.txt","w")
checkallpass('io.close',{{f}})
checkallerrors('io.close',{notanil},'bad argument #1')
-- io.input ([file])
f = io.open("abc.txt","r")
checkallpass('io.input',{{nil,f,"abc.txt"}})
checkallerrors('io.input',{nonstring},'bad argument #1')
-- io.lines ([filename])
io.input("abc.txt")
checkallpass('io.lines',{{nil,"abc.txt"}})
checkallerrors('io.lines',{{f}},'bad argument #1')
checkallerrors('io.lines',{nonstring},'bad argument #1')
-- io.open (filename [, mode])
checkallpass('io.open',{{"abc.txt"},{nil,"r","w","a","r+","w+","a+"}})
checkallerrors('io.open',{notastring},'bad argument #1')
checkallerrors('io.open',{{"abc.txt"},{nonstring}},'bad argument #2')
-- io.output ([file])
checkallpass('io.output',{{nil,f,"abc.txt"}})
checkallerrors('io.output',{nonstring},'bad argument #1')
-- io.popen (prog [, mode])
checkallpass('io.popen',{{"hostname"},{nil,"r","w","a","r+","w+","a+"}})
checkallerrors('io.popen',{notastring},'bad argument #1')
checkallerrors('io.popen',{{"hostname"},{nonstring}},'bad argument #2')
-- io.read (···)
local areadfmt = {2,"*n","*a","*l","3"}
checkallpass('io.read',{})
checkallpass('io.read',{areadfmt})
checkallpass('io.read',{areadfmt,areadfmt})
checkallerrors('io.read',{{aboolean,afunction,atable}},'bad argument #1')
-- io.read (···)
checkallpass('io.write',{})
checkallpass('io.write',{somestring})
checkallpass('io.write',{somestring,somestring})
checkallerrors('io.write',{nonstring},'bad argument #1')
checkallerrors('io.write',{somestring,nonstring},'bad argument #2')
-- file:write ()
file = io.open("seektest.txt","w")
checkallpass('file.write',{{file},somestring})
checkallpass('file.write',{{file},somestring,somestring})
checkallerrors('file.write',{},'bad argument #1')
checkallerrors('file.write',{{file},nonstring},'bad argument #1')
checkallerrors('file.write',{{file},somestring,nonstring},'bad argument #2')
pcall( file.close, file )
-- file:seek ([whence] [, offset])
file = io.open("seektest.txt","r")
checkallpass('file.seek',{{file}})
checkallpass('file.seek',{{file},{"set","cur","end"}})
checkallpass('file.seek',{{file},{"set","cur","end"},{2,"3"}})
checkallerrors('file.seek',{},'bad argument #1')
checkallerrors('file.seek',{{file},nonstring},'bad argument #1')
checkallerrors('file.seek',{{file},{"set","cur","end"},nonnumber},'bad argument #2')
-- file:setvbuf (mode [, size])
checkallpass('file.setvbuf',{{file},{"no","full","line"}})
checkallpass('file.setvbuf',{{file},{"full"},{1024,"512"}})
checkallerrors('file.setvbuf',{},'bad argument #1')
checkallerrors('file.setvbuf',{{file},notastring},'bad argument #1')
checkallerrors('file.setvbuf',{{file},{"full"},nonnumber},'bad argument #2')

View File

@@ -1,106 +0,0 @@
package.path = "?.lua;src/test/errors/?.lua"
require 'args'
-- arg type tests for math library functions
local somenumber = {1,0.75,'-1','-0.25'}
local somepositive = {1,0.75,'2', '2.5'}
local notanumber = {nil,astring,aboolean,afunction,atable,athread}
local nonnumber = {astring,aboolean,afunction,atable}
local singleargfunctions = {
'abs', 'acos', 'asin', 'atan', 'cos', 'cosh', 'deg', 'exp', 'floor',
'rad', 'randomseed', 'sin', 'sinh', 'tan', 'tanh', 'frexp',
}
local singleargposdomain = {
'log', 'log10', 'sqrt', 'ceil',
}
local twoargfunctions = {
'atan2',
}
local twoargsposdomain = {
'pow', 'fmod',
}
-- single argument tests
for i,v in ipairs(singleargfunctions) do
local funcname = 'math.'..v
banner(funcname)
checkallpass(funcname,{somenumber})
checkallerrors(funcname,{notanumber},'bad argument #1')
end
-- single argument, positive domain tests
for i,v in ipairs(singleargposdomain) do
local funcname = 'math.'..v
banner(funcname)
checkallpass(funcname,{somepositive})
checkallerrors(funcname,{notanumber},'bad argument #1')
end
-- two-argument tests
for i,v in ipairs(twoargfunctions) do
local funcname = 'math.'..v
banner(funcname)
checkallpass(funcname,{somenumber,somenumber})
checkallerrors(funcname,{},'bad argument #')
checkallerrors(funcname,{notanumber},'bad argument #')
checkallerrors(funcname,{notanumber,somenumber},'bad argument #1')
checkallerrors(funcname,{somenumber},'bad argument #2')
checkallerrors(funcname,{somenumber,notanumber},'bad argument #2')
end
-- two-argument, positive domain tests
for i,v in ipairs(twoargsposdomain) do
local funcname = 'math.'..v
banner(funcname)
checkallpass(funcname,{somepositive,somenumber})
checkallerrors(funcname,{},'bad argument #')
checkallerrors(funcname,{notanumber},'bad argument #')
checkallerrors(funcname,{notanumber,somenumber},'bad argument #1')
checkallerrors(funcname,{somenumber},'bad argument #2')
checkallerrors(funcname,{somenumber,notanumber},'bad argument #2')
end
-- math.max
banner('math.max')
checkallpass('math.max',{somenumber})
checkallpass('math.max',{somenumber,somenumber})
checkallerrors('math.max',{},'bad argument #1')
checkallerrors('math.max',{nonnumber},'bad argument #1')
checkallerrors('math.max',{somenumber,nonnumber},'bad argument #2')
-- math.min
banner('math.min')
checkallpass('math.min',{somenumber})
checkallpass('math.min',{somenumber,somenumber})
checkallerrors('math.min',{},'bad argument #1')
checkallerrors('math.min',{nonnumber},'bad argument #1')
checkallerrors('math.min',{somenumber,nonnumber},'bad argument #2')
-- math.random
local somem = {3,4.5,'6.7'}
local somen = {8,9.10,'12.34'}
local notamn = {astring,aboolean,atable,afunction}
banner('math.random')
checkallpass('math.random',{},true)
checkallpass('math.random',{somem},true)
checkallpass('math.random',{somem,somen},true)
checkallpass('math.random',{{-4,-5.6,'-7','-8.9'},{-1,100,23.45,'-1.23'}},true)
checkallerrors('math.random',{{-4,-5.6,'-7','-8.9'}},'interval is empty')
checkallerrors('math.random',{somen,somem},'interval is empty')
checkallerrors('math.random',{notamn,somen},'bad argument #1')
checkallerrors('math.random',{somem,notamn},'bad argument #2')
-- math.ldexp
local somee = {-3,0,3,9.10,'12.34'}
local notae = {nil,astring,aboolean,atable,afunction}
banner('math.ldexp')
checkallpass('math.ldexp',{somenumber,somee})
checkallerrors('math.ldexp',{},'bad argument')
checkallerrors('math.ldexp',{notanumber},'bad argument')
checkallerrors('math.ldexp',{notanumber,somee},'bad argument #1')
checkallerrors('math.ldexp',{somenumber},'bad argument #2')
checkallerrors('math.ldexp',{somenumber,notae},'bad argument #2')

View File

@@ -1,49 +0,0 @@
package.path = "?.lua;src/test/errors/?.lua"
require 'args'
-- arg type tests for module library functions
-- require
banner('require')
checkallpass('require',{{'math','coroutine','package','string','table'}},true)
checkallerrors('require',{{anumber}},'not found')
checkallerrors('require',{{anil,aboolean,afunction,atable}},'bad argument')
-- package.loadlib
banner('package.loadlib')
checkallpass('package.loadlib',{{'foo'},{'bar'}},true)
checkallerrors('package.loadlib',{notastring},'bad argument')
-- package.seeall
banner('package.seeall')
checkallpass('package.seeall',{sometable})
checkallerrors('package.seeall',{notatable},'bad argument')
-- module tests - require special rigging
banner('module')
print( pcall( function()
checkallpass('module',{{20001}})
end ) )
print( pcall( function()
checkallpass('module',{{20002},{package.seeall}})
end ) )
print( pcall( function()
checkallpass('module',{{20003},{package.seeall},{function() end}})
end ) )
print( pcall( function()
checkallerrors('module',{{aboolean,atable,function() end}},'bad argument')
checkallerrors('module',{{aboolean,atable,function() end},{package.seeall}},'bad argument')
end ) )
print( pcall( function()
checkallerrors('module',{{'testmodule1'},{'pqrs'}},'attempt to call')
end ) )
print( pcall( function()
checkallerrors('module',{{'testmodule2'},{aboolean}},'attempt to call')
end ) )
print( pcall( function()
checkallerrors('module',{{'testmodule3'},{athread}},'attempt to call')
end ) )
print( pcall( function()
checkallerrors('module',{{'testmodule4'},{atable}},'attempt to call')
end ) )

View File

@@ -1,157 +0,0 @@
package.path = "?.lua;src/test/errors/?.lua"
require 'args'
-- arg types for language operator
-- ========= unary operators: - # not
-- unary minus -
banner('unary -')
negative = function(a) return - a end
checkallpass('negative',{somenumber})
checkallerrors('negative',{notanumber},'attempt to perform arithmetic on')
-- length
banner('#')
lengthop = function(a) return #a end
checkallpass('lengthop',{sometable})
checkallerrors('lengthop',{notatable},'attempt to get length of')
-- length
banner('not')
notop = function(a) return not a end
checkallpass('notop',{somenumber})
checkallerrors('notop',{notanumber},'attempt to perform arithmetic on')
-- function call
banner( '()' )
funcop = function(a) return a() end
checkallpass('funcop',{somefunction})
checkallerrors('funcop',{notafunction},'attempt to call')
-- ========= binary ops: .. + - * / % ^ == ~= <= >= < > [] . and or
banner( '..' )
concatop = function(a,b) return a..b end
checkallpass('concatop',{somestring,somestring})
checkallerrors('concatop',{notastring,somestring},'attempt to concatenate')
checkallerrors('concatop',{somestring,notastring},'attempt to concatenate')
banner( '+' )
plusop = function(a,b) return a+b end
checkallpass('plusop',{somenumber,somenumber})
checkallerrors('plusop',{notanumber,somenumber},'attempt to perform arithmetic on')
checkallerrors('plusop',{somenumber,notanumber},'attempt to perform arithmetic on')
banner( '-' )
minusop = function(a,b) return a-b end
checkallpass('minusop',{somenumber,somenumber})
checkallerrors('minusop',{notanumber,somenumber},'attempt to perform arithmetic on')
checkallerrors('minusop',{somenumber,notanumber},'attempt to perform arithmetic on')
banner( '*' )
timesop = function(a,b) return a*b end
checkallpass('timesop',{somenumber,somenumber})
checkallerrors('timesop',{notanumber,somenumber},'attempt to perform arithmetic on')
checkallerrors('timesop',{somenumber,notanumber},'attempt to perform arithmetic on')
banner( '/' )
divideop = function(a,b) return a/b end
checkallpass('divideop',{somenumber,somenumber})
checkallerrors('divideop',{notanumber,somenumber},'attempt to perform arithmetic on')
checkallerrors('divideop',{somenumber,notanumber},'attempt to perform arithmetic on')
banner( '%' )
modop = function(a,b) return a%b end
checkallpass('modop',{somenumber,somenumber})
checkallerrors('modop',{notanumber,somenumber},'attempt to perform arithmetic on')
checkallerrors('modop',{somenumber,notanumber},'attempt to perform arithmetic on')
banner( '^' )
powerop = function(a,b) return a^b end
checkallpass('powerop',{{2,'2.5'},{3,'3.5'}})
checkallerrors('powerop',{notanumber,{3,'3.1'}},'attempt to perform arithmetic on')
checkallerrors('powerop',{{2,'2.1'},notanumber},'attempt to perform arithmetic on')
banner( '==' )
equalsop = function(a,b) return a==b end
checkallpass('equalsop',{anylua,anylua})
banner( '~=' )
noteqop = function(a,b) return a~=b end
checkallpass('noteqop',{anylua,anylua})
banner( '<=' )
leop = function(a,b) return a<=b end
checkallpass('leop',{{anumber},{anumber}})
checkallpass('leop',{{astring,astrnum},{astring,astrnum}})
checkallerrors('leop',{notanumber,{anumber}},'attempt to compare')
checkallerrors('leop',{{astrnum},{anumber}},'attempt to compare')
checkallerrors('leop',{notastring,{astring,astrnum}},'attempt to compare')
checkallerrors('leop',{{anumber},notanumber},'attempt to compare')
checkallerrors('leop',{{anumber},{astrnum}},'attempt to compare')
checkallerrors('leop',{{astring,astrnum},notastring},'attempt to compare')
banner( '>=' )
geop = function(a,b) return a>=b end
checkallpass('geop',{{anumber},{anumber}})
checkallpass('geop',{{astring,astrnum},{astring,astrnum}})
checkallerrors('geop',{notanumber,{anumber}},'attempt to compare')
checkallerrors('geop',{{astrnum},{anumber}},'attempt to compare')
checkallerrors('geop',{notastring,{astring,astrnum}},'attempt to compare')
checkallerrors('geop',{{anumber},notanumber},'attempt to compare')
checkallerrors('geop',{{anumber},{astrnum}},'attempt to compare')
checkallerrors('geop',{{astring,astrnum},notastring},'attempt to compare')
banner( '<' )
ltop = function(a,b) return a<b end
checkallpass('ltop',{{anumber},{anumber}})
checkallpass('ltop',{{astring,astrnum},{astring,astrnum}})
checkallerrors('ltop',{notanumber,{anumber}},'attempt to compare')
checkallerrors('ltop',{{astrnum},{anumber}},'attempt to compare')
checkallerrors('ltop',{notastring,{astring,astrnum}},'attempt to compare')
checkallerrors('ltop',{{anumber},notanumber},'attempt to compare')
checkallerrors('ltop',{{anumber},{astrnum}},'attempt to compare')
checkallerrors('ltop',{{astring,astrnum},notastring},'attempt to compare')
banner( '>' )
gtop = function(a,b) return a>b end
checkallpass('gtop',{{anumber},{anumber}})
checkallpass('gtop',{{astring,astrnum},{astring,astrnum}})
checkallerrors('gtop',{notanumber,{anumber}},'attempt to compare')
checkallerrors('gtop',{{astrnum},{anumber}},'attempt to compare')
checkallerrors('gtop',{notastring,{astring,astrnum}},'attempt to compare')
checkallerrors('gtop',{{anumber},notanumber},'attempt to compare')
checkallerrors('gtop',{{anumber},{astrnum}},'attempt to compare')
checkallerrors('gtop',{{astring,astrnum},notastring},'attempt to compare')
banner( '[]' )
bracketop = function(a,b) return a[b] end
checkallpass('bracketop',{sometable,notanil})
checkallerrors('bracketop',{notatable,notanil},'attempt to index')
checkallerrors('bracketop',{sometable},'attempt to index')
banner( '.' )
dotop = function(a,b) return a.b end
checkallpass('dotop',{sometable,notanil})
checkallerrors('dotop',{notatable,notanil},'attempt to index')
checkallerrors('dotop',{sometable},'attempt to index')
banner( 'and' )
types = {['table']='table',['function']='function',['thread']='thread'}
clean = function(x) return types[type(x)] or x end
andop = function(a,b) return clean(a and b) end
checkallpass('andop',{anylua,anylua})
banner( 'or' )
orop = function(a,b) return clean(a or b) end
checkallpass('orop',{anylua,anylua})
-- ========= for x in y
banner( 'for x=a,b,c' )
forop = function(a,b,c) for x=a,b,c do end end
checkallpass('forop',{{1,'1.1'},{10,'10.1'},{2,'2.1'}})
checkallerrors('forop',{notanumber,{10,'10.1'},{2,'2.1'}},"'for' initial value must be a number")
checkallerrors('forop',{{1,'1.1'},notanumber,{2,'2.1'}},"'for' limit must be a number")
checkallerrors('forop',{{1,'1.1'},{10,'10.1'},notanumber},"'for' step must be a number")

View File

@@ -1,121 +0,0 @@
package.path = "?.lua;src/test/errors/?.lua"
require 'args'
-- arg type tests for string library functions
-- string.byte
banner('string.byte')
checkallpass('string.byte',{somestring})
checkallpass('string.byte',{somestring,somenumber})
checkallpass('string.byte',{somestring,somenumber,somenumber})
checkallerrors('string.byte',{somestring,{astring,afunction,atable}},'bad argument')
checkallerrors('string.byte',{notastring,{nil,111}},'bad argument')
-- string.char
function string_char(...)
return string.byte( string.char( ... ) )
end
banner('string_char')
checkallpass('string.char',{{60}})
checkallpass('string.char',{{60},{70}})
checkallpass('string.char',{{60},{70},{80}})
checkallpass('string_char',{{nil,0,9,40,127,128,255,'0','9','255','9.2',9.2}})
checkallpass('string_char',{{0,127,255},{0,127,255}})
checkallpass('string_char',{})
checkallerrors('string_char',{},'bad argument #1')
checkallerrors('string_char',{{-1,256}},'bad argument #1')
checkallerrors('string_char',{notanumber,{23,'45',6.7}},'bad argument #1')
checkallerrors('string_char',{{23,'45',6.7},nonnumber},'bad argument #2')
-- string.dump
banner('string.dump')
local someupval = 435
local function funcwithupvals() return someupval end
checkallpass('string.dump',{{function() return 123 end}})
checkallpass('string.dump',{{funcwithupvals}})
checkallerrors('string.dump',{notafunction},'bad argument')
-- string.find
banner('string.find')
checkallpass('string.find',{somestring,somestring})
checkallpass('string.find',{somestring,somestring,{nil,-3,3}})
checkallpass('string.find',{somestring,somestring,somenumber,anylua})
checkallerrors('string.find',{notastring,somestring},'bad argument #1')
checkallerrors('string.find',{somestring,notastring},'bad argument #2')
checkallerrors('string.find',{somestring,somestring,nonnumber},'bad argument #3')
-- string.format
--local numfmts = {'%c','%d','%E','%e','%f','%g','%G','%i','%o','%u','%X','%x'}
local numfmts = {'%c','%d','%i','%o','%u','%X','%x'}
local strfmts = {'%q','%s'}
local badfmts = {'%w'}
banner('string.format')
checkallpass('string.format',{somestring,anylua})
checkallpass('string.format',{numfmts,somenumber})
checkallpass('string.format',{strfmts,somestring})
checkallerrors('string.format',{numfmts,notanumber},'bad argument #2')
checkallerrors('string.format',{strfmts,notastring},'bad argument #2')
checkallerrors('string.format',{badfmts,somestring},"invalid option '%w'")
-- string.gmatch
banner('string.gmatch')
checkallpass('string.gmatch',{somestring,somestring})
checkallerrors('string.gmatch',{notastring,somestring},'bad argument #1')
checkallerrors('string.gmatch',{somestring,notastring},'bad argument #2')
-- string.gsub
local somerepl = {astring,atable,afunction}
local notarepl = {nil,aboolean}
banner('string.gsub')
checkallpass('string.gsub',{somestring,somestring,somerepl,{nil,-1}})
checkallerrors('string.gsub',{nonstring,somestring,somerepl},'bad argument #1')
checkallerrors('string.gsub',{somestring,nonstring,somerepl},'bad argument #2')
checkallerrors('string.gsub',{{astring},{astring},notarepl},'bad argument')
checkallerrors('string.gsub',{{astring},{astring},somerepl,nonnumber},'bad argument #4')
-- string.len
banner('string.len')
checkallpass('string.len',{somestring})
checkallerrors('string.len',{notastring},'bad argument #1')
-- string.lower
banner('string.lower')
checkallpass('string.lower',{somestring})
checkallerrors('string.lower',{notastring},'bad argument #1')
-- string.match
banner('string.match')
checkallpass('string.match',{somestring,somestring})
checkallpass('string.match',{somestring,somestring,{nil,-3,3}})
checkallerrors('string.match',{},'bad argument #1')
checkallerrors('string.match',{nonstring,somestring},'bad argument #1')
checkallerrors('string.match',{somestring},'bad argument #2')
checkallerrors('string.match',{somestring,nonstring},'bad argument #2')
checkallerrors('string.match',{somestring,somestring,notanumber},'bad argument #3')
-- string.reverse
banner('string.reverse')
checkallpass('string.reverse',{somestring})
checkallerrors('string.reverse',{notastring},'bad argument #1')
-- string.rep
banner('string.rep')
checkallpass('string.rep',{somestring,somenumber})
checkallerrors('string.rep',{notastring,somenumber},'bad argument #1')
checkallerrors('string.rep',{somestring,notanumber},'bad argument #2')
-- string.sub
banner('string.sub')
checkallpass('string.sub',{somestring,somenumber})
checkallpass('string.sub',{somestring,somenumber,somenumber})
checkallerrors('string.sub',{},'bad argument #1')
checkallerrors('string.sub',{nonstring,somenumber,somenumber},'bad argument #1')
checkallerrors('string.sub',{somestring},'bad argument #2')
checkallerrors('string.sub',{somestring,nonnumber,somenumber},'bad argument #2')
checkallerrors('string.sub',{somestring,somenumber,nonnumber},'bad argument #3')
-- string.upper
banner('string.upper')
checkallpass('string.upper',{somestring})
checkallerrors('string.upper',{notastring},'bad argument #1')

View File

@@ -1,66 +0,0 @@
package.path = "?.lua;src/test/errors/?.lua"
require 'args'
-- arg type tests for table library functions
-- table.concat
local somestringstable = {{8,7,6,5,4,3,2,1,}}
local somenonstringtable = {{true,true,true,true,true,true,true,true,}}
local somesep = {',',1.23}
local notasep = {aboolean,atable,afunction}
local somei = {2,'2','2.2'}
local somej = {4,'4','4.4'}
local notij = {astring,aboolean,atable,afunction}
banner('table.concat')
checkallpass('table.concat',{somestringstable})
checkallpass('table.concat',{somestringstable,somesep})
checkallpass('table.concat',{somestringstable,{'-'},somei})
checkallpass('table.concat',{somestringstable,{'-'},{2},somej})
checkallerrors('table.concat',{notatable},'bad argument #1')
checkallerrors('table.concat',{somenonstringtable},'table contains non-strings')
checkallerrors('table.concat',{somestringstable,notasep},'bad argument #2')
checkallerrors('table.concat',{somestringstable,{'-'},notij},'bad argument #3')
checkallerrors('table.concat',{somestringstable,{'-'},{2},notij},'bad argument #4')
-- table.insert
banner('table.insert')
checkallpass('table.insert',{sometable,notanil})
checkallpass('table.insert',{sometable,somei,notanil})
checkallerrors('table.insert',{notatable,somestring},'bad argument #1')
checkallerrors('table.insert',{sometable,notij,notanil},'bad argument #2')
-- table.maxn
banner('table.maxn')
checkallpass('table.maxn',{sometable})
checkallerrors('table.maxn',{notatable},'bad argument #1')
-- table.remove
banner('table.remove')
checkallpass('table.remove',{sometable})
checkallpass('table.remove',{sometable,somei})
checkallerrors('table.remove',{notatable},'bad argument #1')
checkallerrors('table.remove',{notatable,somei},'bad argument #1')
checkallerrors('table.remove',{sometable,notij},'bad argument #2')
-- table.sort
local somecomp = {nil,afunction}
local notacomp = {astring,anumber,aboolean,atable}
banner('table.sort')
checkallpass('table.sort',{somestringstable,somecomp})
checkallerrors('table.sort',{sometable},'attempt to compare')
checkallerrors('table.sort',{notatable,somecomp},'bad argument #1')
checkallerrors('table.sort',{sometable,notacomp},'bad argument #2')
-- table get
banner('table_get - tbl[key]')
function table_get(tbl,key) return tbl[key] end
checkallpass('table_get',{sometable,anylua})
-- table set
banner('table_set - tbl[key]=val')
function table_set(tbl,key,val) tbl[key]=val end
function table_set_nil_key(tbl,val) tbl[nil]=val end
checkallpass('table_set',{sometable,notanil,anylua})
checkallerrors('table_set_nil_key',{sometable,anylua},'table index is nil')

View File

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

View File

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

View File

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

View File

@@ -1,102 +0,0 @@
package org.luaj.vm;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.luaj.vm.LString;
import junit.framework.TestCase;
public class LStringTest extends TestCase {
public void testToInputStream() throws IOException {
LString str = new LString("Hello");
InputStream is = str.toInputStream();
assertEquals( 'H', is.read() );
assertEquals( 'e', is.read() );
assertEquals( 2, is.skip( 2 ) );
assertEquals( 'o', is.read() );
assertEquals( -1, is.read() );
assertTrue( is.markSupported() );
is.reset();
assertEquals( 'H', is.read() );
is.mark( 4 );
assertEquals( 'e', is.read() );
is.reset();
assertEquals( 'e', is.read() );
LString substr = str.substring( 1, 4 );
assertEquals( 3, substr.length() );
is.close();
is = substr.toInputStream();
assertEquals( 'e', is.read() );
assertEquals( 'l', is.read() );
assertEquals( 'l', is.read() );
assertEquals( -1, is.read() );
is = substr.toInputStream();
is.reset();
assertEquals( 'e', is.read() );
}
private static final String userFriendly( String s ) {
StringBuffer sb = new StringBuffer();
for ( int i=0, n=s.length(); i<n; i++ ) {
int c = s.charAt(i);
if ( c < ' ' || c >= 0x80 ) {
sb.append( "\\u"+Integer.toHexString(0x10000+c).substring(1) );
} else {
sb.append( (char) c );
}
}
return sb.toString();
}
public 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);
LString ls = new LString(before);
String after = ls.toJavaString();
assertEquals( userFriendly( before ), userFriendly( after ) );
}
char[] c = { (char) (1), (char) (2), (char) (3) };
String before = new String(c)+" 1-3";
LString ls = new LString(before);
String after = ls.toJavaString();
assertEquals( userFriendly( before ), userFriendly( after ) );
}
public void testSpotCheckUtf8() throws UnsupportedEncodingException {
byte[] bytes = {(byte)194,(byte)160,(byte)194,(byte)161,(byte)194,(byte)162,(byte)194,(byte)163,(byte)194,(byte)164};
String expected = new String(bytes, "UTF8");
String actual = new LString(bytes).toJavaString();
char[] d = actual.toCharArray();
assertEquals(160, d[0]);
assertEquals(161, d[1]);
assertEquals(162, d[2]);
assertEquals(163, d[3]);
assertEquals(164, d[4]);
}
public void testNullTerminated() {
char[] c = { 'a', 'b', 'c', '\0', 'd', 'e', 'f' };
String before = new String(c);
LString ls = new LString(before);
String after = ls.toJavaString();
assertEquals( userFriendly( "abc" ), userFriendly( after ) );
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,51 +0,0 @@
-- The Computer Language Benchmarks Game
-- http://shootout.alioth.debian.org/
-- contributed by Mike Pall
local function fannkuch(n)
local p, q, s, odd, check, maxflips = {}, {}, {}, true, 0, 0
for i=1,n do p[i] = i; q[i] = i; s[i] = i end
repeat
-- Print max. 30 permutations.
if check < 30 then
if not p[n] then return maxflips end -- Catch n = 0, 1, 2.
io.write(unpack(p)); io.write("\n")
check = check + 1
end
-- Copy and flip.
local q1 = p[1] -- Cache 1st element.
if p[n] ~= n and q1 ~= 1 then -- Avoid useless work.
for i=2,n do q[i] = p[i] end -- Work on a copy.
for flips=1,1000000 do -- Flip ...
local qq = q[q1]
if qq == 1 then -- ... until 1st element is 1.
if flips > maxflips then maxflips = flips end -- New maximum?
break
end
q[q1] = q1
if q1 >= 4 then
local i, j = 2, q1 - 1
repeat q[i], q[j] = q[j], q[i]; i = i + 1; j = j - 1; until i >= j
end
q1 = qq
end
end
-- Permute.
if odd then
p[2], p[1] = p[1], p[2]; odd = false -- Rotate 1<-2.
else
p[2], p[3] = p[3], p[2]; odd = true -- Rotate 1<-2 and 1<-2<-3.
for i=3,n do
local sx = s[i]
if sx ~= 1 then s[i] = sx-1; break end
if i == n then return maxflips end -- Out of permutations.
s[i] = i
-- Rotate 1<-...<-i+1.
local t = p[1]; for j=1,i do p[j] = p[j+1] end; p[i+1] = t
end
end
until false
end
local n = tonumber(arg and arg[1]) or 1
io.write("Pfannkuchen(", n, ") = ", fannkuch(n), "\n")

View File

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

View File

@@ -1,123 +0,0 @@
-- The Great Computer Language Shootout
-- http://shootout.alioth.debian.org/
-- contributed by Isaac Gouy, tuned by Mike Pall
local sqrt = math.sqrt
local PI = 3.141592653589793
local SOLAR_MASS = 4 * PI * PI
local DAYS_PER_YEAR = 365.24
local Jupiter = {
x = 4.84143144246472090e+00
,y = -1.16032004402742839e+00
,z = -1.03622044471123109e-01
,vx = 1.66007664274403694e-03 * DAYS_PER_YEAR
,vy = 7.69901118419740425e-03 * DAYS_PER_YEAR
,vz = -6.90460016972063023e-05 * DAYS_PER_YEAR
,mass = 9.54791938424326609e-04 * SOLAR_MASS
}
local Saturn = {
x = 8.34336671824457987e+00
,y = 4.12479856412430479e+00
,z = -4.03523417114321381e-01
,vx = -2.76742510726862411e-03 * DAYS_PER_YEAR
,vy = 4.99852801234917238e-03 * DAYS_PER_YEAR
,vz = 2.30417297573763929e-05 * DAYS_PER_YEAR
,mass = 2.85885980666130812e-04 * SOLAR_MASS
}
local Uranus = {
x = 1.28943695621391310e+01
,y = -1.51111514016986312e+01
,z = -2.23307578892655734e-01
,vx = 2.96460137564761618e-03 * DAYS_PER_YEAR
,vy = 2.37847173959480950e-03 * DAYS_PER_YEAR
,vz = -2.96589568540237556e-05 * DAYS_PER_YEAR
,mass = 4.36624404335156298e-05 * SOLAR_MASS
}
local Neptune = {
x = 1.53796971148509165e+01
,y = -2.59193146099879641e+01
,z = 1.79258772950371181e-01
,vx = 2.68067772490389322e-03 * DAYS_PER_YEAR
,vy = 1.62824170038242295e-03 * DAYS_PER_YEAR
,vz = -9.51592254519715870e-05 * DAYS_PER_YEAR
,mass = 5.15138902046611451e-05 * SOLAR_MASS
}
local Sun = { x = 0, y = 0, z = 0,
vx = 0, vy = 0, vz = 0, mass = SOLAR_MASS }
local function advance(bodies, nbody, dt)
for i=1,nbody do
local bi = bodies[i]
local bix, biy, biz, bimass = bi.x, bi.y, bi.z, bi.mass
local bivx, bivy, bivz = bi.vx, bi.vy, bi.vz
for j=i+1,nbody do
local bj = bodies[j]
local dx, dy, dz = bix-bj.x, biy-bj.y, biz-bj.z
local distance = sqrt(dx*dx + dy*dy + dz*dz)
local mag = dt / (distance * distance * distance)
local bim, bjm = bimass*mag, bj.mass*mag
bivx = bivx - (dx * bjm)
bivy = bivy - (dy * bjm)
bivz = bivz - (dz * bjm)
bj.vx = bj.vx + (dx * bim)
bj.vy = bj.vy + (dy * bim)
bj.vz = bj.vz + (dz * bim)
end
bi.vx = bivx
bi.vy = bivy
bi.vz = bivz
end
for i=1,nbody do
local bi = bodies[i]
bi.x = bi.x + (dt * bi.vx)
bi.y = bi.y + (dt * bi.vy)
bi.z = bi.z + (dt * bi.vz)
end
end
local function energy(bodies, nbody)
local e = 0
for i=1,nbody do
local bi = bodies[i]
local vx, vy, vz, bim = bi.vx, bi.vy, bi.vz, bi.mass
e = e + (0.5 * bim * (vx*vx + vy*vy + vz*vz))
for j=i+1,nbody do
local bj = bodies[j]
local dx, dy, dz = bi.x-bj.x, bi.y-bj.y, bi.z-bj.z
local distance = sqrt(dx*dx + dy*dy + dz*dz)
e = e - ((bim * bj.mass) / distance)
end
end
return e
end
local function offsetMomentum(b, nbody)
local px, py, pz = 0, 0, 0
for i=1,nbody do
local bi = b[i]
local bim = bi.mass
px = px + (bi.vx * bim)
py = py + (bi.vy * bim)
pz = pz + (bi.vz * bim)
end
b[1].vx = -px / SOLAR_MASS
b[1].vy = -py / SOLAR_MASS
b[1].vz = -pz / SOLAR_MASS
end
local N = tonumber(arg and arg[1]) or 1000
local bodies = { Sun, Jupiter, Saturn, Uranus, Neptune }
local nbody = table.getn(bodies)
offsetMomentum(bodies, nbody)
io.write( string.format("%0.9f",energy(bodies, nbody)), "\n")
for i=1,N do advance(bodies, nbody, 0.01) end
io.write( string.format("%0.9f",energy(bodies, nbody)), "\n")