interplane.Get Omega
Read in your language

lua

[Ported from github.com/lua/lua] Cast in 'rl_readline_name'

Brought by drakestapleton

branch master Branches Tags History

lua / testes / main.lua

602 lines · 16291 bytes Raw Blame History
1# testing special comment on first line
2-- $Id: testes/main.lua $
3-- See Copyright Notice in file lua.h
4
5-- most (all?) tests here assume a reasonable "Unix-like" shell
6if _port then return end
7
8-- use only "double quotes" inside shell scripts (better change to
9-- run on Windows)
10
11
12print ("testing stand-alone interpreter")
13
14assert(os.execute()) -- machine has a system command
15
16local arg = arg or ARG
17
18local prog = os.tmpname()
19local otherprog = os.tmpname()
20local out = os.tmpname()
21
22local progname
23do
24 local i = 0
25 while arg[i] do i=i-1 end
26 progname = arg[i+1]
27end
28print("progname: "..progname)
29
30
31local prepfile = function (s, mod, p)
32 mod = mod and "wb" or "w" -- mod true means binary files
33 p = p or prog -- file to write the program
34 local f = io.open(p, mod)
35 f:write(s)
36 assert(f:close())
37end
38
39local function getoutput ()
40 local f = io.open(out)
41 local t = f:read("a")
42 f:close()
43 assert(os.remove(out))
44 return t
45end
46
47local function checkprogout (s)
48 -- expected result must end with new line
49 assert(string.sub(s, -1) == "\n")
50 local t = getoutput()
51 for line in string.gmatch(s, ".-\n") do
52 assert(string.find(t, line, 1, true))
53 end
54end
55
56local function checkout (s)
57 local t = getoutput()
58 if s ~= t then print(string.format("'%s' - '%s'\n", s, t)) end
59 assert(s == t)
60 return t
61end
62
63
64local function RUN (p, ...)
65 p = string.gsub(p, "lua", '"'..progname..'"', 1)
66 local s = string.format(p, ...)
67 assert(os.execute(s))
68end
69
70
71local function NoRun (msg, p, ...)
72 p = string.gsub(p, "lua", '"'..progname..'"', 1)
73 local s = string.format(p, ...)
74 s = string.format("%s >%s 2>&1", s, out) -- send output and error to 'out'
75 assert(not os.execute(s))
76 assert(string.find(getoutput(), msg, 1, true)) -- check error message
77end
78
79RUN('lua -v')
80
81RUN('lua -v > %s', out)
82local release = string.match(getoutput(), "Lua (%d+%.%d+%.%d+)")
83
84print(string.format("(temporary program file used in these tests: %s)", prog))
85
86-- running stdin as a file
87prepfile""
88RUN('lua - < %s > %s', prog, out)
89checkout("")
90
91prepfile[[
92 print(
931, a
94)
95]]
96RUN('lua - -- < %s > %s', prog, out)
97checkout("1\tnil\n")
98
99RUN('echo "print(10)\nprint(2)\n" | lua > %s', out)
100checkout("10\n2\n")
101
102
103-- testing BOM
104prepfile("\xEF\xBB\xBF")
105RUN('lua %s > %s', prog, out)
106checkout("")
107
108prepfile("\xEF\xBB\xBFprint(3)")
109RUN('lua %s > %s', prog, out)
110checkout("3\n")
111
112prepfile("\xEF\xBB\xBF# comment!!\nprint(3)")
113RUN('lua %s > %s', prog, out)
114checkout("3\n")
115
116-- bad BOMs
117prepfile("\xEF", true)
118NoRun("unexpected symbol", 'lua %s', prog)
119
120prepfile("\xEF\xBB", true)
121NoRun("unexpected symbol", 'lua %s', prog)
122
123prepfile("\xEFprint(3)", true)
124NoRun("unexpected symbol", 'lua %s', prog)
125
126prepfile("\xEF\xBBprint(3)", true)
127NoRun("unexpected symbol", 'lua %s', prog)
128
129
130-- test option '-'
131RUN('echo "print(arg[1])" | lua - -h > %s', out)
132checkout("-h\n")
133
134-- test environment variables used by Lua
135
136prepfile("print(package.path)")
137
138-- test LUA_PATH
139RUN('env LUA_INIT= LUA_PATH=x lua -- %s > %s', prog, out)
140checkout("x\n")
141
142-- test LUA_PATH_version
143RUN('env LUA_INIT= LUA_PATH_5_5=y LUA_PATH=x lua %s > %s', prog, out)
144checkout("y\n")
145
146-- test LUA_CPATH
147prepfile("print(package.cpath)")
148RUN('env LUA_INIT= LUA_CPATH=xuxu lua %s > %s', prog, out)
149checkout("xuxu\n")
150
151-- test LUA_CPATH_version
152RUN('env LUA_INIT= LUA_CPATH_5_5=yacc LUA_CPATH=x lua %s > %s', prog, out)
153checkout("yacc\n")
154
155-- test LUA_INIT (and its access to 'arg' table)
156prepfile("print(X)")
157RUN('env LUA_INIT="X=tonumber(arg[1])" lua %s 3.2 > %s', prog, out)
158checkout("3.2\n")
159
160-- test LUA_INIT_version
161prepfile("print(X)")
162RUN('env LUA_INIT_5_5="X=10" LUA_INIT="X=3" lua %s > %s', prog, out)
163checkout("10\n")
164
165-- test LUA_INIT for files
166prepfile("x = x or 10; print(x); x = x + 1")
167RUN('env LUA_INIT="@%s" lua %s > %s', prog, prog, out)
168checkout("10\n11\n")
169
170-- test errors in LUA_INIT
171NoRun('LUA_INIT:1: msg', 'env LUA_INIT="error(\'msg\')" lua')
172
173
174print("testing option '-E'")
175
176local defaultpath, defaultCpath
177
178do
179 prepfile("print(package.path, package.cpath)")
180 RUN('env LUA_INIT="error(10)" LUA_PATH=xxx LUA_CPATH=xxx lua -E %s > %s',
181 prog, out)
182 local output = getoutput()
183 defaultpath = string.match(output, "^(.-)\t")
184 defaultCpath = string.match(output, "\t(.-)$")
185
186 -- running with an empty environment
187 RUN('env -i lua %s > %s', prog, out)
188 local out = getoutput()
189 assert(defaultpath == string.match(output, "^(.-)\t"))
190 assert(defaultCpath == string.match(output, "\t(.-)$"))
191end
192
193-- paths did not change
194assert(not string.find(defaultpath, "xxx") and
195 string.find(defaultpath, "lua") and
196 not string.find(defaultCpath, "xxx") and
197 string.find(defaultCpath, "lua"))
198
199
200-- (LUA_READLINELIB was introduced in 5.5.1)
201if release >= "5.5.1" then
202 -- OBS: this test is not valid when Lua is compiled with LUA_USE_READLINE
203 print"testing readline library name"
204 -- should generate a warning when trying to load inexistent library "xuxu"
205 local env = [[LUA_READLINELIB=xuxu LUA_INIT="warn('@allow')"]]
206 local code = 'echo " " | env %s lua %s -W -i >%s 2>&1'
207 RUN(code, env, "", out) -- run code with no extra options
208 if(not string.find(getoutput(),
209 "warning: unable to load readline library 'xuxu'")) then
210 error("Is Lua compiled with option LUA_USE_READLINE?")
211 end
212 RUN(code, env, "-E", out) -- run again with option -E
213 -- no warning when LUA_READLINELIB is to be ignored
214 assert(not string.find(getoutput(), "warning"))
215end
216
217
218-- test replacement of ';;' to default path
219local function convert (p)
220 prepfile("print(package.path)")
221 RUN('env LUA_PATH="%s" lua %s > %s', p, prog, out)
222 local expected = getoutput()
223 expected = string.sub(expected, 1, -2) -- cut final end of line
224 if string.find(p, ";;") then
225 p = string.gsub(p, ";;", ";"..defaultpath..";")
226 p = string.gsub(p, "^;", "") -- remove ';' at the beginning
227 p = string.gsub(p, ";$", "") -- remove ';' at the end
228 end
229 assert(p == expected)
230end
231
232convert(";")
233convert(";;")
234convert("a;;b")
235convert(";;b")
236convert("a;;")
237convert("a;b;;c")
238
239
240-- test -l over multiple libraries
241prepfile("print(1); a=2; return {x=15}")
242prepfile(("print(a); print(_G['%s'].x)"):format(prog), false, otherprog)
243RUN('env LUA_PATH="?;;" lua -l %s -l%s -lstring -l io %s > %s', prog, otherprog, otherprog, out)
244checkout("1\n2\n15\n2\n15\n")
245
246-- test explicit global names in -l
247prepfile("print(str.upper'alo alo', m.max(10, 20))")
248RUN("lua -l 'str=string' '-lm=math' -e 'print(m.sin(0))' %s > %s", prog, out)
249checkout("0.0\nALO ALO\t20\n")
250
251
252-- test module names with version suffix ("libs/lib2-v2")
253RUN("env LUA_CPATH='./libs/?.so' lua -l lib2-v2 -e 'print(lib2.id())' > %s",
254 out)
255checkout("true\n")
256
257
258-- test 'arg' table
259local a = [[
260 assert(#arg == 3 and arg[1] == 'a' and
261 arg[2] == 'b' and arg[3] == 'c')
262 assert(arg[-1] == '--' and arg[-2] == "-e " and arg[-3] == '%s')
263 assert(arg[4] == undef and arg[-4] == undef)
264 local a, b, c = ...
265 assert(... == 'a' and a == 'a' and b == 'b' and c == 'c')
266]]
267a = string.format(a, progname)
268prepfile(a)
269RUN('lua "-e " -- %s a b c', prog) -- "-e " runs an empty command
270
271-- test 'arg' availability in libraries
272prepfile"assert(arg)"
273prepfile("assert(arg)", false, otherprog)
274RUN('env LUA_PATH="?;;" lua -l%s - < %s', prog, otherprog)
275
276-- test messing up the 'arg' table
277RUN('echo "print(...)" | lua -e "arg[1] = 100" - > %s', out)
278checkout("100\n")
279NoRun("'arg' is not a table", 'echo "" | lua -e "arg = 1" -')
280
281-- test error in 'print'
282RUN('echo 10 | lua -e "print=nil" -i > /dev/null 2> %s', out)
283assert(string.find(getoutput(), "error calling 'print'"))
284
285-- test 'debug.debug'
286RUN('echo "io.stderr:write(1000)\ncont" | lua -e "require\'debug\'.debug()" 2> %s', out)
287checkout("lua_debug> 1000lua_debug> ")
288
289do -- test warning for locals
290 RUN('echo " local x" | lua -i > %s 2>&1', out)
291 assert(string.find(getoutput(), "warning: "))
292
293 RUN('echo "local1 = 10\nlocal1 + 3" | lua -i > %s 2>&1', out)
294 local t = getoutput()
295 assert(not string.find(t, "warning"))
296 assert(string.find(t, "13"))
297end
298
299print("testing warnings")
300
301-- no warnings by default
302RUN('echo "io.stderr:write(1); warn[[XXX]]" | lua 2> %s', out)
303checkout("1")
304
305prepfile[[
306warn("@allow") -- unknown control, ignored
307warn("@off", "XXX", "@off") -- these are not control messages
308warn("@off") -- this one is
309warn("@on", "YYY", "@on") -- not control, but warn is off
310warn("@off") -- keep it off
311warn("@on") -- restart warnings
312warn("", "@on") -- again, no control, real warning
313warn("@on") -- keep it "started"
314warn("Z", "Z", "Z") -- common warning
315]]
316RUN('lua -W %s 2> %s', prog, out)
317checkout[[
318Lua warning: @offXXX@off
319Lua warning: @on
320Lua warning: ZZZ
321]]
322
323prepfile[[
324warn("@allow")
325-- create two objects to be finalized when closing state
326-- the errors in the finalizers must generate warnings
327u1 = setmetatable({}, {__gc = function () error("XYZ") end})
328u2 = setmetatable({}, {__gc = function () error("ZYX") end})
329]]
330RUN('lua -W %s 2> %s', prog, out)
331checkprogout("ZYX)\nXYZ)\n")
332
333-- bug since 5.2: finalizer called when closing a state could
334-- subvert finalization order
335prepfile[[
336-- ensure tables will be collected only at the end of the program
337collectgarbage"stop"
338
339print("creating 1")
340-- this finalizer should be called last
341setmetatable({}, {__gc = function () print(1) end})
342
343print("creating 2")
344setmetatable({}, {__gc = function ()
345 print("2")
346 print("creating 3")
347 -- this finalizer should not be called, as object will be
348 -- created after 'lua_close' has been called
349 setmetatable({}, {__gc = function () print(3) end})
350 print(collectgarbage() or false) -- cannot call collector here
351 os.exit(0, true)
352end})
353]]
354RUN('lua -W %s > %s', prog, out)
355checkout[[
356creating 1
357creating 2
3582
359creating 3
360false
3611
362]]
363
364
365-- test many arguments
366prepfile[[print(({...})[30])]]
367RUN('lua %s %s > %s', prog, string.rep(" a", 30), out)
368checkout("a\n")
369
370RUN([[lua "-eprint(1)" -ea=3 -e "print(a)" > %s]], out)
371checkout("1\n3\n")
372
373-- test interactive mode
374prepfile[[
375(6*2-6) -- ===
376a =
37710
378print(a)
379a]]
380RUN([[lua -e"_PROMPT='' _PROMPT2=''" -i < %s > %s]], prog, out)
381checkprogout("6\n10\n10\n\n")
382
383prepfile("a = [[b\nc\nd\ne]]\na")
384RUN([[lua -e"_PROMPT='' _PROMPT2=''" -i -- < %s > %s]], prog, out)
385checkprogout("b\nc\nd\ne\n\n")
386
387-- input interrupted in continuation line
388prepfile("a.\n")
389RUN([[lua -i < %s > /dev/null 2> %s]], prog, out)
390checkprogout("near <eof>\n")
391
392local prompt = "alo"
393prepfile[[ --
394a = 2
395]]
396RUN([[lua "-e_PROMPT='%s'" -i < %s > %s]], prompt, prog, out)
397local t = getoutput()
398assert(string.find(t, prompt .. ".*" .. prompt .. ".*" .. prompt))
399
400-- using the prompt default
401prepfile[[ --
402a = 2
403]]
404RUN([[lua -i < %s > %s]], prog, out)
405local t = getoutput()
406prompt = "> " -- the default
407assert(string.find(t, prompt .. ".*" .. prompt .. ".*" .. prompt))
408
409
410-- non-string prompt
411prompt = [[
412 local C = 'X';
413 _PROMPT=setmetatable({},{__tostring = function ()
414 C = C .. 'X'; return C end})
415]]
416prepfile[[ --
417a = 2
418]]
419RUN([[lua -e "%s" -i < %s > %s]], prompt, prog, out)
420local t = getoutput()
421-- skip version line and then check the presence of the three prompts
422assert(string.find(t, "^.-\nXX[^\nX]*\n?XXX[^\nX]*\n?XXXX\n?$"))
423
424
425-- test for error objects
426prepfile[[
427debug = require "debug"
428m = {x=0}
429setmetatable(m, {__tostring = function(x)
430 return tostring(debug.getinfo(4).currentline + x.x)
431end})
432error(m)
433]]
434NoRun(progname .. ": 6\n", [[lua %s]], prog)
435
436prepfile("error{}")
437NoRun("error object is a table value", [[lua %s]], prog)
438
439
440-- chunk broken in many lines
441local s = [=[ --
442function f ( x )
443 local a = [[
444xuxu
445]]
446 local b = "\
447xuxu\n"
448 if x == 11 then return 1 + 12 , 2 + 20 end --[[ test multiple returns ]]
449 return x + 1
450 --\\
451end
452return( f( 100 ) )
453assert( a == b )
454do return f( 11 ) end ]=]
455s = string.gsub(s, ' ', '\n\n') -- change all spaces for newlines
456prepfile(s)
457RUN([[lua -e"_PROMPT='' _PROMPT2=''" -i < %s > %s]], prog, out)
458checkprogout("101\n13\t22\n\n")
459
460prepfile[[#comment in 1st line without \n at the end]]
461RUN('lua %s', prog)
462
463-- first-line comment with binary file
464prepfile("#comment\n" .. string.dump(load("print(3)")), true)
465RUN('lua %s > %s', prog, out)
466checkout('3\n')
467
468-- close Lua with an open file
469prepfile(string.format([[io.output(%q); io.write('alo')]], out))
470RUN('lua %s', prog)
471checkout('alo')
472
473-- bug in 5.2 beta (extra \0 after version line)
474RUN([[lua -v -e"print'hello'" > %s]], out)
475t = getoutput()
476assert(string.find(t, "PUC%-Rio\nhello"))
477
478
479-- testing os.exit
480prepfile("os.exit(nil, true)")
481RUN('lua %s', prog)
482prepfile("os.exit(0, true)")
483RUN('lua %s', prog)
484prepfile("os.exit(true, true)")
485RUN('lua %s', prog)
486prepfile("os.exit(1, true)")
487NoRun("", "lua %s", prog) -- no message
488prepfile("os.exit(false, true)")
489NoRun("", "lua %s", prog) -- no message
490
491
492-- to-be-closed variables in main chunk
493prepfile[[
494 local x <close> = setmetatable({},
495 {__close = function (self, err)
496 assert(err == nil)
497 print("Ok")
498 end})
499 local e1 <close> = setmetatable({}, {__close = function () print(120) end})
500 os.exit(true, true)
501]]
502RUN('lua %s > %s', prog, out)
503checkprogout("120\nOk\n")
504
505
506-- remove temporary files
507assert(os.remove(prog))
508assert(os.remove(otherprog))
509assert(not os.remove(out))
510
511-- invalid options
512NoRun("unrecognized option '-h'", "lua -h")
513NoRun("unrecognized option '---'", "lua ---")
514NoRun("unrecognized option '-Ex'", "lua -Ex --")
515NoRun("unrecognized option '-vv'", "lua -vv")
516NoRun("unrecognized option '-iv'", "lua -iv")
517NoRun("'-e' needs argument", "lua -e")
518NoRun("syntax error", "lua -e a")
519NoRun("'-l' needs argument", "lua -l")
520NoRun("-i", "lua -- -i") -- handles -i as a script name
521
522
523if T then -- test library?
524 print("testing 'not enough memory' to create a state")
525 NoRun("not enough memory", "env MEMLIMIT=100 lua")
526
527 -- testing 'warn'
528 warn("@store")
529 warn("@123", "456", "789")
530 assert(_WARN == "@123456789"); _WARN = false
531
532 warn("zip", "", " ", "zap")
533 assert(_WARN == "zip zap"); _WARN = false
534 warn("ZIP", "", " ", "ZAP")
535 assert(_WARN == "ZIP ZAP"); _WARN = false
536 warn("@normal")
537end
538
539do
540 -- 'warn' must get at least one argument
541 local st, msg = pcall(warn)
542 assert(string.find(msg, "string expected"))
543
544 -- 'warn' does not leave unfinished warning in case of errors
545 -- (message would appear in next warning)
546 st, msg = pcall(warn, "SHOULD NOT APPEAR", {})
547 assert(string.find(msg, "string expected"))
548end
549
550print('+')
551
552print('testing Ctrl C')
553do
554 -- interrupt a script
555 local function kill (pid)
556 return os.execute(string.format('kill -INT %s 2> /dev/null', pid))
557 end
558
559 -- function to run a script in background, returning its output file
560 -- descriptor and its pid
561 local function runback (luaprg)
562 -- shell script to run 'luaprg' in background and echo its pid
563 local shellprg = string.format('%s -e "%s" & echo $!', progname, luaprg)
564 local f = io.popen(shellprg, "r") -- run shell script
565 local pid = f:read() -- get pid for Lua script
566 print("(if test fails now, it may leave a Lua script running in \z
567 background, pid " .. pid .. ")")
568 return f, pid
569 end
570
571 -- Lua script that runs protected infinite loop and then prints '42'
572 local f, pid = runback[[
573 pcall(function () print(12); while true do end end); print(42)]]
574 -- wait until script is inside 'pcall'
575 assert(f:read() == "12")
576 kill(pid) -- send INT signal to Lua script
577 -- check that 'pcall' captured the exception and script continued running
578 assert(f:read() == "42") -- expected output
579 assert(f:close())
580 print("done")
581
582 -- Lua script in a long unbreakable search
583 local f, pid = runback[[
584 print(15); string.find(string.rep('a', 100000), '.*b')]]
585 -- wait (so script can reach the loop)
586 assert(f:read() == "15")
587 assert(os.execute("sleep 1"))
588 -- must send at least two INT signals to stop this Lua script
589 local n = 100
590 for i = 0, 100 do -- keep sending signals
591 if not kill(pid) then -- until it fails
592 n = i -- number of non-failed kills
593 break
594 end
595 end
596 assert(f:close())
597 assert(n >= 2)
598 print(string.format("done (with %d kills)", n))
599
600end
601
602print("OK")