main.lua 14 KB

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