main.lua 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. # testing special comment on first line
  2. -- $Id: testes/main.lua $
  3. -- See Copyright Notice in file all.lua
  4. -- most (all?) tests here assume a reasonable "Unix-like" shell
  5. if _port then return end
  6. -- use only "double quotes" inside shell scripts (better change to
  7. -- run on Windows)
  8. print ("testing stand-alone interpreter")
  9. assert(os.execute()) -- machine has a system command
  10. local arg = arg or ARG
  11. local prog = os.tmpname()
  12. local otherprog = os.tmpname()
  13. local out = os.tmpname()
  14. local progname
  15. do
  16. local i = 0
  17. while arg[i] do i=i-1 end
  18. progname = arg[i+1]
  19. end
  20. print("progname: "..progname)
  21. local prepfile = function (s, p)
  22. p = p or prog
  23. io.output(p)
  24. io.write(s)
  25. assert(io.close())
  26. end
  27. local function getoutput ()
  28. io.input(out)
  29. local t = io.read("a")
  30. io.input():close()
  31. assert(os.remove(out))
  32. return t
  33. end
  34. local function checkprogout (s)
  35. -- expected result must end with new line
  36. assert(string.sub(s, -1) == "\n")
  37. local t = getoutput()
  38. for line in string.gmatch(s, ".-\n") do
  39. assert(string.find(t, line, 1, true))
  40. end
  41. end
  42. local function checkout (s)
  43. local t = getoutput()
  44. if s ~= t then print(string.format("'%s' - '%s'\n", s, t)) end
  45. assert(s == t)
  46. return t
  47. end
  48. local function RUN (p, ...)
  49. p = string.gsub(p, "lua", '"'..progname..'"', 1)
  50. local s = string.format(p, ...)
  51. assert(os.execute(s))
  52. end
  53. local function NoRun (msg, p, ...)
  54. p = string.gsub(p, "lua", '"'..progname..'"', 1)
  55. local s = string.format(p, ...)
  56. s = string.format("%s 2> %s", s, out) -- will send error to 'out'
  57. assert(not os.execute(s))
  58. assert(string.find(getoutput(), msg, 1, true)) -- check error message
  59. end
  60. RUN('lua -v')
  61. print(string.format("(temporary program file used in these tests: %s)", prog))
  62. -- running stdin as a file
  63. prepfile""
  64. RUN('lua - < %s > %s', prog, out)
  65. checkout("")
  66. prepfile[[
  67. print(
  68. 1, a
  69. )
  70. ]]
  71. RUN('lua - < %s > %s', prog, out)
  72. checkout("1\tnil\n")
  73. RUN('echo "print(10)\nprint(2)\n" | lua > %s', out)
  74. checkout("10\n2\n")
  75. -- test option '-'
  76. RUN('echo "print(arg[1])" | lua - -h > %s', out)
  77. checkout("-h\n")
  78. -- test environment variables used by Lua
  79. prepfile("print(package.path)")
  80. -- test LUA_PATH
  81. RUN('env LUA_INIT= LUA_PATH=x lua %s > %s', prog, out)
  82. checkout("x\n")
  83. -- test LUA_PATH_version
  84. RUN('env LUA_INIT= LUA_PATH_5_4=y LUA_PATH=x lua %s > %s', prog, out)
  85. checkout("y\n")
  86. -- test LUA_CPATH
  87. prepfile("print(package.cpath)")
  88. RUN('env LUA_INIT= LUA_CPATH=xuxu lua %s > %s', prog, out)
  89. checkout("xuxu\n")
  90. -- test LUA_CPATH_version
  91. RUN('env LUA_INIT= LUA_CPATH_5_4=yacc LUA_CPATH=x lua %s > %s', prog, out)
  92. checkout("yacc\n")
  93. -- test LUA_INIT (and its access to 'arg' table)
  94. prepfile("print(X)")
  95. RUN('env LUA_INIT="X=tonumber(arg[1])" lua %s 3.2 > %s', prog, out)
  96. checkout("3.2\n")
  97. -- test LUA_INIT_version
  98. prepfile("print(X)")
  99. RUN('env LUA_INIT_5_4="X=10" LUA_INIT="X=3" lua %s > %s', prog, out)
  100. checkout("10\n")
  101. -- test LUA_INIT for files
  102. prepfile("x = x or 10; print(x); x = x + 1")
  103. RUN('env LUA_INIT="@%s" lua %s > %s', prog, prog, out)
  104. checkout("10\n11\n")
  105. -- test errors in LUA_INIT
  106. NoRun('LUA_INIT:1: msg', 'env LUA_INIT="error(\'msg\')" lua')
  107. -- test option '-E'
  108. local defaultpath, defaultCpath
  109. do
  110. prepfile("print(package.path, package.cpath)")
  111. RUN('env LUA_INIT="error(10)" LUA_PATH=xxx LUA_CPATH=xxx lua -E %s > %s',
  112. prog, out)
  113. local output = getoutput()
  114. defaultpath = string.match(output, "^(.-)\t")
  115. defaultCpath = string.match(output, "\t(.-)$")
  116. -- running with an empty environment
  117. RUN('env -i lua %s > %s', prog, out)
  118. local out = getoutput()
  119. assert(defaultpath == string.match(output, "^(.-)\t"))
  120. assert(defaultCpath == string.match(output, "\t(.-)$"))
  121. end
  122. -- paths did not change
  123. assert(not string.find(defaultpath, "xxx") and
  124. string.find(defaultpath, "lua") and
  125. not string.find(defaultCpath, "xxx") and
  126. string.find(defaultCpath, "lua"))
  127. -- test replacement of ';;' to default path
  128. local function convert (p)
  129. prepfile("print(package.path)")
  130. RUN('env LUA_PATH="%s" lua %s > %s', p, prog, out)
  131. local expected = getoutput()
  132. expected = string.sub(expected, 1, -2) -- cut final end of line
  133. if string.find(p, ";;") then
  134. p = string.gsub(p, ";;", ";"..defaultpath..";")
  135. p = string.gsub(p, "^;", "") -- remove ';' at the beginning
  136. p = string.gsub(p, ";$", "") -- remove ';' at the end
  137. end
  138. assert(p == expected)
  139. end
  140. convert(";")
  141. convert(";;")
  142. convert("a;;b")
  143. convert(";;b")
  144. convert("a;;")
  145. convert("a;b;;c")
  146. -- test -l over multiple libraries
  147. prepfile("print(1); a=2; return {x=15}")
  148. prepfile(("print(a); print(_G['%s'].x)"):format(prog), otherprog)
  149. RUN('env LUA_PATH="?;;" lua -l %s -l%s -lstring -l io %s > %s', prog, otherprog, otherprog, out)
  150. checkout("1\n2\n15\n2\n15\n")
  151. -- test explicit global names in -l
  152. prepfile("print(str.upper'alo alo', m.max(10, 20))")
  153. RUN("lua -l 'str=string' '-lm=math' -e 'print(m.sin(0))' %s > %s", prog, out)
  154. checkout("0.0\nALO ALO\t20\n")
  155. -- test 'arg' table
  156. local a = [[
  157. assert(#arg == 3 and arg[1] == 'a' and
  158. arg[2] == 'b' and arg[3] == 'c')
  159. assert(arg[-1] == '--' and arg[-2] == "-e " and arg[-3] == '%s')
  160. assert(arg[4] == undef and arg[-4] == undef)
  161. local a, b, c = ...
  162. assert(... == 'a' and a == 'a' and b == 'b' and c == 'c')
  163. ]]
  164. a = string.format(a, progname)
  165. prepfile(a)
  166. RUN('lua "-e " -- %s a b c', prog) -- "-e " runs an empty command
  167. -- test 'arg' availability in libraries
  168. prepfile"assert(arg)"
  169. prepfile("assert(arg)", otherprog)
  170. RUN('env LUA_PATH="?;;" lua -l%s - < %s', prog, otherprog)
  171. -- test messing up the 'arg' table
  172. RUN('echo "print(...)" | lua -e "arg[1] = 100" - > %s', out)
  173. checkout("100\n")
  174. NoRun("'arg' is not a table", 'echo "" | lua -e "arg = 1" -')
  175. -- test error in 'print'
  176. RUN('echo 10 | lua -e "print=nil" -i > /dev/null 2> %s', out)
  177. assert(string.find(getoutput(), "error calling 'print'"))
  178. -- test 'debug.debug'
  179. RUN('echo "io.stderr:write(1000)\ncont" | lua -e "require\'debug\'.debug()" 2> %s', out)
  180. checkout("lua_debug> 1000lua_debug> ")
  181. print("testing warnings")
  182. -- no warnings by default
  183. RUN('echo "io.stderr:write(1); warn[[XXX]]" | lua 2> %s', out)
  184. checkout("1")
  185. prepfile[[
  186. warn("@allow") -- unknown control, ignored
  187. warn("@off", "XXX", "@off") -- these are not control messages
  188. warn("@off") -- this one is
  189. warn("@on", "YYY", "@on") -- not control, but warn is off
  190. warn("@off") -- keep it off
  191. warn("@on") -- restart warnings
  192. warn("", "@on") -- again, no control, real warning
  193. warn("@on") -- keep it "started"
  194. warn("Z", "Z", "Z") -- common warning
  195. ]]
  196. RUN('lua -W %s 2> %s', prog, out)
  197. checkout[[
  198. Lua warning: @offXXX@off
  199. Lua warning: @on
  200. Lua warning: ZZZ
  201. ]]
  202. prepfile[[
  203. warn("@allow")
  204. -- create two objects to be finalized when closing state
  205. -- the errors in the finalizers must generate warnings
  206. u1 = setmetatable({}, {__gc = function () error("XYZ") end})
  207. u2 = setmetatable({}, {__gc = function () error("ZYX") end})
  208. ]]
  209. RUN('lua -W %s 2> %s', prog, out)
  210. checkprogout("ZYX)\nXYZ)\n")
  211. -- bug since 5.2: finalizer called when closing a state could
  212. -- subvert finalization order
  213. prepfile[[
  214. -- should be called last
  215. print("creating 1")
  216. setmetatable({}, {__gc = function () print(1) end})
  217. print("creating 2")
  218. setmetatable({}, {__gc = function ()
  219. print("2")
  220. print("creating 3")
  221. -- this finalizer should not be called, as object will be
  222. -- created after 'lua_close' has been called
  223. setmetatable({}, {__gc = function () print(3) end})
  224. print(collectgarbage()) -- cannot call collector here
  225. os.exit(0, true)
  226. end})
  227. ]]
  228. RUN('lua -W %s > %s', prog, out)
  229. checkout[[
  230. creating 1
  231. creating 2
  232. 2
  233. creating 3
  234. nil
  235. 1
  236. ]]
  237. -- test many arguments
  238. prepfile[[print(({...})[30])]]
  239. RUN('lua %s %s > %s', prog, string.rep(" a", 30), out)
  240. checkout("a\n")
  241. RUN([[lua "-eprint(1)" -ea=3 -e "print(a)" > %s]], out)
  242. checkout("1\n3\n")
  243. -- test iteractive mode
  244. prepfile[[
  245. (6*2-6) -- ===
  246. a =
  247. 10
  248. print(a)
  249. a]]
  250. RUN([[lua -e"_PROMPT='' _PROMPT2=''" -i < %s > %s]], prog, out)
  251. checkprogout("6\n10\n10\n\n")
  252. prepfile("a = [[b\nc\nd\ne]]\n=a")
  253. RUN([[lua -e"_PROMPT='' _PROMPT2=''" -i < %s > %s]], prog, out)
  254. checkprogout("b\nc\nd\ne\n\n")
  255. prompt = "alo"
  256. prepfile[[ --
  257. a = 2
  258. ]]
  259. RUN([[lua "-e_PROMPT='%s'" -i < %s > %s]], prompt, prog, out)
  260. local t = getoutput()
  261. assert(string.find(t, prompt .. ".*" .. prompt .. ".*" .. prompt))
  262. -- using the prompt default
  263. prepfile[[ --
  264. a = 2
  265. ]]
  266. RUN([[lua -i < %s > %s]], prog, out)
  267. local t = getoutput()
  268. prompt = "> " -- the default
  269. assert(string.find(t, prompt .. ".*" .. prompt .. ".*" .. prompt))
  270. -- non-string prompt
  271. prompt =
  272. "local C = 0;\z
  273. _PROMPT=setmetatable({},{__tostring = function () \z
  274. C = C + 1; return C end})"
  275. prepfile[[ --
  276. a = 2
  277. ]]
  278. RUN([[lua -e "%s" -i < %s > %s]], prompt, prog, out)
  279. local t = getoutput()
  280. assert(string.find(t, [[
  281. 1 --
  282. 2a = 2
  283. 3
  284. ]], 1, true))
  285. -- test for error objects
  286. prepfile[[
  287. debug = require "debug"
  288. m = {x=0}
  289. setmetatable(m, {__tostring = function(x)
  290. return tostring(debug.getinfo(4).currentline + x.x)
  291. end})
  292. error(m)
  293. ]]
  294. NoRun(progname .. ": 6\n", [[lua %s]], prog)
  295. prepfile("error{}")
  296. NoRun("error object is a table value", [[lua %s]], prog)
  297. -- chunk broken in many lines
  298. s = [=[ --
  299. function f ( x )
  300. local a = [[
  301. xuxu
  302. ]]
  303. local b = "\
  304. xuxu\n"
  305. if x == 11 then return 1 + 12 , 2 + 20 end --[[ test multiple returns ]]
  306. return x + 1
  307. --\\
  308. end
  309. return( f( 100 ) )
  310. assert( a == b )
  311. do return f( 11 ) end ]=]
  312. s = string.gsub(s, ' ', '\n\n') -- change all spaces for newlines
  313. prepfile(s)
  314. RUN([[lua -e"_PROMPT='' _PROMPT2=''" -i < %s > %s]], prog, out)
  315. checkprogout("101\n13\t22\n\n")
  316. prepfile[[#comment in 1st line without \n at the end]]
  317. RUN('lua %s', prog)
  318. prepfile[[#test line number when file starts with comment line
  319. debug = require"debug"
  320. print(debug.getinfo(1).currentline)
  321. ]]
  322. RUN('lua %s > %s', prog, out)
  323. checkprogout('3\n')
  324. -- close Lua with an open file
  325. prepfile(string.format([[io.output(%q); io.write('alo')]], out))
  326. RUN('lua %s', prog)
  327. checkout('alo')
  328. -- bug in 5.2 beta (extra \0 after version line)
  329. RUN([[lua -v -e"print'hello'" > %s]], out)
  330. t = getoutput()
  331. assert(string.find(t, "PUC%-Rio\nhello"))
  332. -- testing os.exit
  333. prepfile("os.exit(nil, true)")
  334. RUN('lua %s', prog)
  335. prepfile("os.exit(0, true)")
  336. RUN('lua %s', prog)
  337. prepfile("os.exit(true, true)")
  338. RUN('lua %s', prog)
  339. prepfile("os.exit(1, true)")
  340. NoRun("", "lua %s", prog) -- no message
  341. prepfile("os.exit(false, true)")
  342. NoRun("", "lua %s", prog) -- no message
  343. -- to-be-closed variables in main chunk
  344. prepfile[[
  345. local x <close> = setmetatable({},
  346. {__close = function (self, err)
  347. assert(err == nil)
  348. print("Ok")
  349. end})
  350. local e1 <close> = setmetatable({}, {__close = function () print(120) end})
  351. os.exit(true, true)
  352. ]]
  353. RUN('lua %s > %s', prog, out)
  354. checkprogout("120\nOk\n")
  355. -- remove temporary files
  356. assert(os.remove(prog))
  357. assert(os.remove(otherprog))
  358. assert(not os.remove(out))
  359. -- invalid options
  360. NoRun("unrecognized option '-h'", "lua -h")
  361. NoRun("unrecognized option '---'", "lua ---")
  362. NoRun("unrecognized option '-Ex'", "lua -Ex")
  363. NoRun("unrecognized option '-vv'", "lua -vv")
  364. NoRun("unrecognized option '-iv'", "lua -iv")
  365. NoRun("'-e' needs argument", "lua -e")
  366. NoRun("syntax error", "lua -e a")
  367. NoRun("'-l' needs argument", "lua -l")
  368. if T then -- test library?
  369. print("testing 'not enough memory' to create a state")
  370. NoRun("not enough memory", "env MEMLIMIT=100 lua")
  371. -- testing 'warn'
  372. warn("@store")
  373. warn("@123", "456", "789")
  374. assert(_WARN == "@123456789"); _WARN = false
  375. warn("zip", "", " ", "zap")
  376. assert(_WARN == "zip zap"); _WARN = false
  377. warn("ZIP", "", " ", "ZAP")
  378. assert(_WARN == "ZIP ZAP"); _WARN = false
  379. warn("@normal")
  380. end
  381. do
  382. -- 'warn' must get at least one argument
  383. local st, msg = pcall(warn)
  384. assert(string.find(msg, "string expected"))
  385. -- 'warn' does not leave unfinished warning in case of errors
  386. -- (message would appear in next warning)
  387. st, msg = pcall(warn, "SHOULD NOT APPEAR", {})
  388. assert(string.find(msg, "string expected"))
  389. end
  390. print('+')
  391. print('testing Ctrl C')
  392. do
  393. -- interrupt a script
  394. local function kill (pid)
  395. return os.execute(string.format('kill -INT %s 2> /dev/null', pid))
  396. end
  397. -- function to run a script in background, returning its output file
  398. -- descriptor and its pid
  399. local function runback (luaprg)
  400. -- shell script to run 'luaprg' in background and echo its pid
  401. local shellprg = string.format('%s -e "%s" & echo $!', progname, luaprg)
  402. local f = io.popen(shellprg, "r") -- run shell script
  403. local pid = f:read() -- get pid for Lua script
  404. print("(if test fails now, it may leave a Lua script running in \z
  405. background, pid " .. pid .. ")")
  406. return f, pid
  407. end
  408. -- Lua script that runs protected infinite loop and then prints '42'
  409. local f, pid = runback[[
  410. pcall(function () print(12); while true do end end); print(42)]]
  411. -- wait until script is inside 'pcall'
  412. assert(f:read() == "12")
  413. kill(pid) -- send INT signal to Lua script
  414. -- check that 'pcall' captured the exception and script continued running
  415. assert(f:read() == "42") -- expected output
  416. assert(f:close())
  417. print("done")
  418. -- Lua script in a long unbreakable search
  419. local f, pid = runback[[
  420. print(15); string.find(string.rep('a', 100000), '.*b')]]
  421. -- wait (so script can reach the loop)
  422. assert(f:read() == "15")
  423. assert(os.execute("sleep 1"))
  424. -- must send at least two INT signals to stop this Lua script
  425. local n = 100
  426. for i = 0, 100 do -- keep sending signals
  427. if not kill(pid) then -- until it fails
  428. n = i -- number of non-failed kills
  429. break
  430. end
  431. end
  432. assert(f:close())
  433. assert(n >= 2)
  434. print(string.format("done (with %d kills)", n))
  435. end
  436. print("OK")