files.lua 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  1. -- $Id: testes/files.lua $
  2. -- See Copyright Notice in file all.lua
  3. local debug = require "debug"
  4. local maxint = math.maxinteger
  5. assert(type(os.getenv"PATH") == "string")
  6. assert(io.input(io.stdin) == io.stdin)
  7. assert(not pcall(io.input, "non-existent-file"))
  8. assert(io.output(io.stdout) == io.stdout)
  9. local function testerr (msg, f, ...)
  10. local stat, err = pcall(f, ...)
  11. return (not stat and string.find(err, msg, 1, true))
  12. end
  13. local function checkerr (msg, f, ...)
  14. assert(testerr(msg, f, ...))
  15. end
  16. -- cannot close standard files
  17. assert(not io.close(io.stdin) and
  18. not io.stdout:close() and
  19. not io.stderr:close())
  20. -- cannot call close method without an argument (new in 5.3.5)
  21. checkerr("got no value", io.stdin.close)
  22. assert(type(io.input()) == "userdata" and io.type(io.output()) == "file")
  23. assert(type(io.stdin) == "userdata" and io.type(io.stderr) == "file")
  24. assert(not io.type(8))
  25. local a = {}; setmetatable(a, {})
  26. assert(not io.type(a))
  27. assert(getmetatable(io.input()).__name == "FILE*")
  28. local a,b,c = io.open('xuxu_nao_existe')
  29. assert(not a and type(b) == "string" and type(c) == "number")
  30. a,b,c = io.open('/a/b/c/d', 'w')
  31. assert(not a and type(b) == "string" and type(c) == "number")
  32. local file = os.tmpname()
  33. local f, msg = io.open(file, "w")
  34. if not f then
  35. (Message or print)("'os.tmpname' file cannot be open; skipping file tests")
  36. else --{ most tests here need tmpname
  37. f:close()
  38. print('testing i/o')
  39. local otherfile = os.tmpname()
  40. checkerr("invalid mode", io.open, file, "rw")
  41. checkerr("invalid mode", io.open, file, "rb+")
  42. checkerr("invalid mode", io.open, file, "r+bk")
  43. checkerr("invalid mode", io.open, file, "")
  44. checkerr("invalid mode", io.open, file, "+")
  45. checkerr("invalid mode", io.open, file, "b")
  46. assert(io.open(file, "r+b")):close()
  47. assert(io.open(file, "r+")):close()
  48. assert(io.open(file, "rb")):close()
  49. assert(os.setlocale('C', 'all'))
  50. io.input(io.stdin); io.output(io.stdout);
  51. os.remove(file)
  52. assert(not loadfile(file))
  53. checkerr("", dofile, file)
  54. assert(not io.open(file))
  55. io.output(file)
  56. assert(io.output() ~= io.stdout)
  57. if not _port then -- invalid seek
  58. local status, msg, code = io.stdin:seek("set", 1000)
  59. assert(not status and type(msg) == "string" and type(code) == "number")
  60. end
  61. assert(io.output():seek() == 0)
  62. assert(io.write("alo alo"):seek() == string.len("alo alo"))
  63. assert(io.output():seek("cur", -3) == string.len("alo alo")-3)
  64. assert(io.write("joao"))
  65. assert(io.output():seek("end") == string.len("alo joao"))
  66. assert(io.output():seek("set") == 0)
  67. assert(io.write('"alo"', "{a}\n", "second line\n", "third line \n"))
  68. assert(io.write('Xfourth_line'))
  69. io.output(io.stdout)
  70. collectgarbage() -- file should be closed by GC
  71. assert(io.input() == io.stdin and rawequal(io.output(), io.stdout))
  72. print('+')
  73. -- test GC for files
  74. collectgarbage()
  75. for i=1,120 do
  76. for i=1,5 do
  77. io.input(file)
  78. assert(io.open(file, 'r'))
  79. io.lines(file)
  80. end
  81. collectgarbage()
  82. end
  83. io.input():close()
  84. io.close()
  85. assert(os.rename(file, otherfile))
  86. assert(not os.rename(file, otherfile))
  87. io.output(io.open(otherfile, "ab"))
  88. assert(io.write("\n\n\t\t ", 3450, "\n"));
  89. io.close()
  90. do
  91. -- closing file by scope
  92. local F = nil
  93. do
  94. local f <close> = assert(io.open(file, "w"))
  95. F = f
  96. end
  97. assert(tostring(F) == "file (closed)")
  98. end
  99. assert(os.remove(file))
  100. do
  101. -- test writing/reading numbers
  102. local f <close> = assert(io.open(file, "w"))
  103. f:write(maxint, '\n')
  104. f:write(string.format("0X%x\n", maxint))
  105. f:write("0xABCp-3", '\n')
  106. f:write(0, '\n')
  107. f:write(-maxint, '\n')
  108. f:write(string.format("0x%X\n", -maxint))
  109. f:write("-0xABCp-3", '\n')
  110. assert(f:close())
  111. local f <close> = assert(io.open(file, "r"))
  112. assert(f:read("n") == maxint)
  113. assert(f:read("n") == maxint)
  114. assert(f:read("n") == 0xABCp-3)
  115. assert(f:read("n") == 0)
  116. assert(f:read("*n") == -maxint) -- test old format (with '*')
  117. assert(f:read("n") == -maxint)
  118. assert(f:read("*n") == -0xABCp-3) -- test old format (with '*')
  119. end
  120. assert(os.remove(file))
  121. -- testing multiple arguments to io.read
  122. do
  123. local f <close> = assert(io.open(file, "w"))
  124. f:write[[
  125. a line
  126. another line
  127. 1234
  128. 3.45
  129. one
  130. two
  131. three
  132. ]]
  133. local l1, l2, l3, l4, n1, n2, c, dummy
  134. assert(f:close())
  135. local f <close> = assert(io.open(file, "r"))
  136. l1, l2, n1, n2, dummy = f:read("l", "L", "n", "n")
  137. assert(l1 == "a line" and l2 == "another line\n" and
  138. n1 == 1234 and n2 == 3.45 and dummy == nil)
  139. assert(f:close())
  140. local f <close> = assert(io.open(file, "r"))
  141. l1, l2, n1, n2, c, l3, l4, dummy = f:read(7, "l", "n", "n", 1, "l", "l")
  142. assert(l1 == "a line\n" and l2 == "another line" and c == '\n' and
  143. n1 == 1234 and n2 == 3.45 and l3 == "one" and l4 == "two"
  144. and dummy == nil)
  145. assert(f:close())
  146. local f <close> = assert(io.open(file, "r"))
  147. -- second item failing
  148. l1, n1, n2, dummy = f:read("l", "n", "n", "l")
  149. assert(l1 == "a line" and not n1)
  150. end
  151. assert(os.remove(file))
  152. -- test yielding during 'dofile'
  153. f = assert(io.open(file, "w"))
  154. f:write[[
  155. local x, z = coroutine.yield(10)
  156. local y = coroutine.yield(20)
  157. return x + y * z
  158. ]]
  159. assert(f:close())
  160. f = coroutine.wrap(dofile)
  161. assert(f(file) == 10)
  162. assert(f(100, 101) == 20)
  163. assert(f(200) == 100 + 200 * 101)
  164. assert(os.remove(file))
  165. f = assert(io.open(file, "w"))
  166. -- test number termination
  167. f:write[[
  168. -12.3- -0xffff+ .3|5.E-3X +234e+13E 0xDEADBEEFDEADBEEFx
  169. 0x1.13Ap+3e
  170. ]]
  171. -- very long number
  172. f:write("1234"); for i = 1, 1000 do f:write("0") end; f:write("\n")
  173. -- invalid sequences (must read and discard valid prefixes)
  174. f:write[[
  175. .e+ 0.e; --; 0xX;
  176. ]]
  177. assert(f:close())
  178. f = assert(io.open(file, "r"))
  179. assert(f:read("n") == -12.3); assert(f:read(1) == "-")
  180. assert(f:read("n") == -0xffff); assert(f:read(2) == "+ ")
  181. assert(f:read("n") == 0.3); assert(f:read(1) == "|")
  182. assert(f:read("n") == 5e-3); assert(f:read(1) == "X")
  183. assert(f:read("n") == 234e13); assert(f:read(1) == "E")
  184. assert(f:read("n") == 0Xdeadbeefdeadbeef); assert(f:read(2) == "x\n")
  185. assert(f:read("n") == 0x1.13aP3); assert(f:read(1) == "e")
  186. do -- attempt to read too long number
  187. assert(not f:read("n")) -- fails
  188. local s = f:read("L") -- read rest of line
  189. assert(string.find(s, "^00*\n$")) -- lots of 0's left
  190. end
  191. assert(not f:read("n")); assert(f:read(2) == "e+")
  192. assert(not f:read("n")); assert(f:read(1) == ";")
  193. assert(not f:read("n")); assert(f:read(2) == "-;")
  194. assert(not f:read("n")); assert(f:read(1) == "X")
  195. assert(not f:read("n")); assert(f:read(1) == ";")
  196. assert(not f:read("n")); assert(not f:read(0)) -- end of file
  197. assert(f:close())
  198. assert(os.remove(file))
  199. -- test line generators
  200. assert(not pcall(io.lines, "non-existent-file"))
  201. assert(os.rename(otherfile, file))
  202. io.output(otherfile)
  203. local n = 0
  204. local f = io.lines(file)
  205. while f() do n = n + 1 end;
  206. assert(n == 6) -- number of lines in the file
  207. checkerr("file is already closed", f)
  208. checkerr("file is already closed", f)
  209. -- copy from file to otherfile
  210. n = 0
  211. for l in io.lines(file) do io.write(l, "\n"); n = n + 1 end
  212. io.close()
  213. assert(n == 6)
  214. -- copy from otherfile back to file
  215. local f = assert(io.open(otherfile))
  216. assert(io.type(f) == "file")
  217. io.output(file)
  218. assert(not io.output():read())
  219. n = 0
  220. for l in f:lines() do io.write(l, "\n"); n = n + 1 end
  221. assert(tostring(f):sub(1, 5) == "file ")
  222. assert(f:close()); io.close()
  223. assert(n == 6)
  224. checkerr("closed file", io.close, f)
  225. assert(tostring(f) == "file (closed)")
  226. assert(io.type(f) == "closed file")
  227. io.input(file)
  228. f = io.open(otherfile):lines()
  229. n = 0
  230. for l in io.lines() do assert(l == f()); n = n + 1 end
  231. f = nil; collectgarbage()
  232. assert(n == 6)
  233. assert(os.remove(otherfile))
  234. do -- bug in 5.3.1
  235. io.output(otherfile)
  236. io.write(string.rep("a", 300), "\n")
  237. io.close()
  238. local t ={}; for i = 1, 250 do t[i] = 1 end
  239. t = {io.lines(otherfile, table.unpack(t))()}
  240. -- everything ok here
  241. assert(#t == 250 and t[1] == 'a' and t[#t] == 'a')
  242. t[#t + 1] = 1 -- one too many
  243. checkerr("too many arguments", io.lines, otherfile, table.unpack(t))
  244. collectgarbage() -- ensure 'otherfile' is closed
  245. assert(os.remove(otherfile))
  246. end
  247. io.input(file)
  248. do -- test error returns
  249. local a,b,c = io.input():write("xuxu")
  250. assert(not a and type(b) == "string" and type(c) == "number")
  251. end
  252. checkerr("invalid format", io.read, "x")
  253. assert(io.read(0) == "") -- not eof
  254. assert(io.read(5, 'l') == '"alo"')
  255. assert(io.read(0) == "")
  256. assert(io.read() == "second line")
  257. local x = io.input():seek()
  258. assert(io.read() == "third line ")
  259. assert(io.input():seek("set", x))
  260. assert(io.read('L') == "third line \n")
  261. assert(io.read(1) == "X")
  262. assert(io.read(string.len"fourth_line") == "fourth_line")
  263. assert(io.input():seek("cur", -string.len"fourth_line"))
  264. assert(io.read() == "fourth_line")
  265. assert(io.read() == "") -- empty line
  266. assert(io.read('n') == 3450)
  267. assert(io.read(1) == '\n')
  268. assert(not io.read(0)) -- end of file
  269. assert(not io.read(1)) -- end of file
  270. assert(not io.read(30000)) -- end of file
  271. assert(({io.read(1)})[2] == undef)
  272. assert(not io.read()) -- end of file
  273. assert(({io.read()})[2] == undef)
  274. assert(not io.read('n')) -- end of file
  275. assert(({io.read('n')})[2] == undef)
  276. assert(io.read('a') == '') -- end of file (OK for 'a')
  277. assert(io.read('a') == '') -- end of file (OK for 'a')
  278. collectgarbage()
  279. print('+')
  280. io.close(io.input())
  281. checkerr(" input file is closed", io.read)
  282. assert(os.remove(file))
  283. local t = '0123456789'
  284. for i=1,10 do t = t..t; end
  285. assert(string.len(t) == 10*2^10)
  286. io.output(file)
  287. io.write("alo"):write("\n")
  288. io.close()
  289. checkerr(" output file is closed", io.write)
  290. local f = io.open(file, "a+b")
  291. io.output(f)
  292. collectgarbage()
  293. assert(io.write(' ' .. t .. ' '))
  294. assert(io.write(';', 'end of file\n'))
  295. f:flush(); io.flush()
  296. f:close()
  297. print('+')
  298. io.input(file)
  299. assert(io.read() == "alo")
  300. assert(io.read(1) == ' ')
  301. assert(io.read(string.len(t)) == t)
  302. assert(io.read(1) == ' ')
  303. assert(io.read(0))
  304. assert(io.read('a') == ';end of file\n')
  305. assert(not io.read(0))
  306. assert(io.close(io.input()))
  307. -- test errors in read/write
  308. do
  309. local function ismsg (m)
  310. -- error message is not a code number
  311. return (type(m) == "string" and not tonumber(m))
  312. end
  313. -- read
  314. local f = io.open(file, "w")
  315. local r, m, c = f:read()
  316. assert(not r and ismsg(m) and type(c) == "number")
  317. assert(f:close())
  318. -- write
  319. f = io.open(file, "r")
  320. r, m, c = f:write("whatever")
  321. assert(not r and ismsg(m) and type(c) == "number")
  322. assert(f:close())
  323. -- lines
  324. f = io.open(file, "w")
  325. r, m = pcall(f:lines())
  326. assert(r == false and ismsg(m))
  327. assert(f:close())
  328. end
  329. assert(os.remove(file))
  330. -- test for L format
  331. io.output(file); io.write"\n\nline\nother":close()
  332. io.input(file)
  333. assert(io.read"L" == "\n")
  334. assert(io.read"L" == "\n")
  335. assert(io.read"L" == "line\n")
  336. assert(io.read"L" == "other")
  337. assert(not io.read"L")
  338. io.input():close()
  339. local f = assert(io.open(file))
  340. local s = ""
  341. for l in f:lines("L") do s = s .. l end
  342. assert(s == "\n\nline\nother")
  343. f:close()
  344. io.input(file)
  345. s = ""
  346. for l in io.lines(nil, "L") do s = s .. l end
  347. assert(s == "\n\nline\nother")
  348. io.input():close()
  349. s = ""
  350. for l in io.lines(file, "L") do s = s .. l end
  351. assert(s == "\n\nline\nother")
  352. s = ""
  353. for l in io.lines(file, "l") do s = s .. l end
  354. assert(s == "lineother")
  355. io.output(file); io.write"a = 10 + 34\na = 2*a\na = -a\n":close()
  356. local t = {}
  357. assert(load(io.lines(file, "L"), nil, nil, t))()
  358. assert(t.a == -((10 + 34) * 2))
  359. do -- testing closing file in line iteration
  360. -- get the to-be-closed variable from a loop
  361. local function gettoclose (lv)
  362. lv = lv + 1
  363. local stvar = 0 -- to-be-closed is 4th state variable in the loop
  364. for i = 1, 1000 do
  365. local n, v = debug.getlocal(lv, i)
  366. if n == "(for state)" then
  367. stvar = stvar + 1
  368. if stvar == 4 then return v end
  369. end
  370. end
  371. end
  372. local f
  373. for l in io.lines(file) do
  374. f = gettoclose(1)
  375. assert(io.type(f) == "file")
  376. break
  377. end
  378. assert(io.type(f) == "closed file")
  379. f = nil
  380. local function foo (name)
  381. for l in io.lines(name) do
  382. f = gettoclose(1)
  383. assert(io.type(f) == "file")
  384. error(f) -- exit loop with an error
  385. end
  386. end
  387. local st, msg = pcall(foo, file)
  388. assert(st == false and io.type(msg) == "closed file")
  389. end
  390. -- test for multipe arguments in 'lines'
  391. io.output(file); io.write"0123456789\n":close()
  392. for a,b in io.lines(file, 1, 1) do
  393. if a == "\n" then assert(not b)
  394. else assert(tonumber(a) == tonumber(b) - 1)
  395. end
  396. end
  397. for a,b,c in io.lines(file, 1, 2, "a") do
  398. assert(a == "0" and b == "12" and c == "3456789\n")
  399. end
  400. for a,b,c in io.lines(file, "a", 0, 1) do
  401. if a == "" then break end
  402. assert(a == "0123456789\n" and not b and not c)
  403. end
  404. collectgarbage() -- to close file in previous iteration
  405. io.output(file); io.write"00\n10\n20\n30\n40\n":close()
  406. for a, b in io.lines(file, "n", "n") do
  407. if a == 40 then assert(not b)
  408. else assert(a == b - 10)
  409. end
  410. end
  411. -- test load x lines
  412. io.output(file);
  413. io.write[[
  414. local y
  415. = X
  416. X =
  417. X *
  418. 2 +
  419. X;
  420. X =
  421. X
  422. - y;
  423. ]]:close()
  424. _G.X = 1
  425. assert(not load((io.lines(file))))
  426. collectgarbage() -- to close file in previous iteration
  427. load((io.lines(file, "L")))()
  428. assert(_G.X == 2)
  429. load((io.lines(file, 1)))()
  430. assert(_G.X == 4)
  431. load((io.lines(file, 3)))()
  432. assert(_G.X == 8)
  433. _G.X = nil
  434. print('+')
  435. local x1 = "string\n\n\\com \"\"''coisas [[estranhas]] ]]'"
  436. io.output(file)
  437. assert(io.write(string.format("X2 = %q\n-- comment without ending EOS", x1)))
  438. io.close()
  439. assert(loadfile(file))()
  440. assert(x1 == _G.X2)
  441. _G.X2 = nil
  442. print('+')
  443. assert(os.remove(file))
  444. assert(not os.remove(file))
  445. assert(not os.remove(otherfile))
  446. -- testing loadfile
  447. local function testloadfile (s, expres)
  448. io.output(file)
  449. if s then io.write(s) end
  450. io.close()
  451. local res = assert(loadfile(file))()
  452. assert(os.remove(file))
  453. assert(res == expres)
  454. end
  455. -- loading empty file
  456. testloadfile(nil, nil)
  457. -- loading file with initial comment without end of line
  458. testloadfile("# a non-ending comment", nil)
  459. -- checking Unicode BOM in files
  460. testloadfile("\xEF\xBB\xBF# some comment\nreturn 234", 234)
  461. testloadfile("\xEF\xBB\xBFreturn 239", 239)
  462. testloadfile("\xEF\xBB\xBF", nil) -- empty file with a BOM
  463. -- checking line numbers in files with initial comments
  464. testloadfile("# a comment\nreturn require'debug'.getinfo(1).currentline", 2)
  465. -- loading binary file
  466. io.output(io.open(file, "wb"))
  467. assert(io.write(string.dump(function () return 10, '\0alo\255', 'hi' end)))
  468. io.close()
  469. a, b, c = assert(loadfile(file))()
  470. assert(a == 10 and b == "\0alo\255" and c == "hi")
  471. assert(os.remove(file))
  472. -- bug in 5.2.1
  473. do
  474. io.output(io.open(file, "wb"))
  475. -- save function with no upvalues
  476. assert(io.write(string.dump(function () return 1 end)))
  477. io.close()
  478. f = assert(loadfile(file, "b", {}))
  479. assert(type(f) == "function" and f() == 1)
  480. assert(os.remove(file))
  481. end
  482. -- loading binary file with initial comment
  483. io.output(io.open(file, "wb"))
  484. assert(io.write("#this is a comment for a binary file\0\n",
  485. string.dump(function () return 20, '\0\0\0' end)))
  486. io.close()
  487. a, b, c = assert(loadfile(file))()
  488. assert(a == 20 and b == "\0\0\0" and c == nil)
  489. assert(os.remove(file))
  490. -- 'loadfile' with 'env'
  491. do
  492. local f = io.open(file, 'w')
  493. f:write[[
  494. if (...) then a = 15; return b, c, d
  495. else return _ENV
  496. end
  497. ]]
  498. f:close()
  499. local t = {b = 12, c = "xuxu", d = print}
  500. local f = assert(loadfile(file, 't', t))
  501. local b, c, d = f(1)
  502. assert(t.a == 15 and b == 12 and c == t.c and d == print)
  503. assert(f() == t)
  504. f = assert(loadfile(file, 't', nil))
  505. assert(f() == nil)
  506. f = assert(loadfile(file))
  507. assert(f() == _G)
  508. assert(os.remove(file))
  509. end
  510. -- 'loadfile' x modes
  511. do
  512. io.open(file, 'w'):write("return 10"):close()
  513. local s, m = loadfile(file, 'b')
  514. assert(not s and string.find(m, "a text chunk"))
  515. io.open(file, 'w'):write("\27 return 10"):close()
  516. local s, m = loadfile(file, 't')
  517. assert(not s and string.find(m, "a binary chunk"))
  518. assert(os.remove(file))
  519. end
  520. io.output(file)
  521. assert(io.write("qualquer coisa\n"))
  522. assert(io.write("mais qualquer coisa"))
  523. io.close()
  524. assert(io.output(assert(io.open(otherfile, 'wb')))
  525. :write("outra coisa\0\1\3\0\0\0\0\255\0")
  526. :close())
  527. local filehandle = assert(io.open(file, 'r+'))
  528. local otherfilehandle = assert(io.open(otherfile, 'rb'))
  529. assert(filehandle ~= otherfilehandle)
  530. assert(type(filehandle) == "userdata")
  531. assert(filehandle:read('l') == "qualquer coisa")
  532. io.input(otherfilehandle)
  533. assert(io.read(string.len"outra coisa") == "outra coisa")
  534. assert(filehandle:read('l') == "mais qualquer coisa")
  535. filehandle:close();
  536. assert(type(filehandle) == "userdata")
  537. io.input(otherfilehandle)
  538. assert(io.read(4) == "\0\1\3\0")
  539. assert(io.read(3) == "\0\0\0")
  540. assert(io.read(0) == "") -- 255 is not eof
  541. assert(io.read(1) == "\255")
  542. assert(io.read('a') == "\0")
  543. assert(not io.read(0))
  544. assert(otherfilehandle == io.input())
  545. otherfilehandle:close()
  546. assert(os.remove(file))
  547. assert(os.remove(otherfile))
  548. collectgarbage()
  549. io.output(file)
  550. :write[[
  551. 123.4 -56e-2 not a number
  552. second line
  553. third line
  554. and the rest of the file
  555. ]]
  556. :close()
  557. io.input(file)
  558. local _,a,b,c,d,e,h,__ = io.read(1, 'n', 'n', 'l', 'l', 'l', 'a', 10)
  559. assert(io.close(io.input()))
  560. assert(_ == ' ' and not __)
  561. assert(type(a) == 'number' and a==123.4 and b==-56e-2)
  562. assert(d=='second line' and e=='third line')
  563. assert(h==[[
  564. and the rest of the file
  565. ]])
  566. assert(os.remove(file))
  567. collectgarbage()
  568. -- testing buffers
  569. do
  570. local f = assert(io.open(file, "w"))
  571. local fr = assert(io.open(file, "r"))
  572. assert(f:setvbuf("full", 2000))
  573. f:write("x")
  574. assert(fr:read("all") == "") -- full buffer; output not written yet
  575. f:close()
  576. fr:seek("set")
  577. assert(fr:read("all") == "x") -- `close' flushes it
  578. f = assert(io.open(file), "w")
  579. assert(f:setvbuf("no"))
  580. f:write("x")
  581. fr:seek("set")
  582. assert(fr:read("all") == "x") -- no buffer; output is ready
  583. f:close()
  584. f = assert(io.open(file, "a"))
  585. assert(f:setvbuf("line"))
  586. f:write("x")
  587. fr:seek("set", 1)
  588. assert(fr:read("all") == "") -- line buffer; no output without `\n'
  589. f:write("a\n"):seek("set", 1)
  590. assert(fr:read("all") == "xa\n") -- now we have a whole line
  591. f:close(); fr:close()
  592. assert(os.remove(file))
  593. end
  594. if not _soft then
  595. print("testing large files (> BUFSIZ)")
  596. io.output(file)
  597. for i=1,5001 do io.write('0123456789123') end
  598. io.write('\n12346'):close()
  599. io.input(file)
  600. local x = io.read('a')
  601. io.input():seek('set', 0)
  602. local y = io.read(30001)..io.read(1005)..io.read(0)..
  603. io.read(1)..io.read(100003)
  604. assert(x == y and string.len(x) == 5001*13 + 6)
  605. io.input():seek('set', 0)
  606. y = io.read() -- huge line
  607. assert(x == y..'\n'..io.read())
  608. assert(not io.read())
  609. io.close(io.input())
  610. assert(os.remove(file))
  611. x = nil; y = nil
  612. end
  613. if not _port then
  614. local progname
  615. do -- get name of running executable
  616. local arg = arg or ARG
  617. local i = 0
  618. while arg[i] do i = i - 1 end
  619. progname = '"' .. arg[i + 1] .. '"'
  620. end
  621. print("testing popen/pclose and execute")
  622. -- invalid mode for popen
  623. checkerr("invalid mode", io.popen, "cat", "")
  624. checkerr("invalid mode", io.popen, "cat", "r+")
  625. checkerr("invalid mode", io.popen, "cat", "rw")
  626. do -- basic tests for popen
  627. local file = os.tmpname()
  628. local f = assert(io.popen("cat - > " .. file, "w"))
  629. f:write("a line")
  630. assert(f:close())
  631. local f = assert(io.popen("cat - < " .. file, "r"))
  632. assert(f:read("a") == "a line")
  633. assert(f:close())
  634. assert(os.remove(file))
  635. end
  636. local tests = {
  637. -- command, what, code
  638. {"ls > /dev/null", "ok"},
  639. {"not-to-be-found-command", "exit"},
  640. {"exit 3", "exit", 3},
  641. {"exit 129", "exit", 129},
  642. {"kill -s HUP $$", "signal", 1},
  643. {"kill -s KILL $$", "signal", 9},
  644. {"sh -c 'kill -s HUP $$'", "exit"},
  645. {progname .. ' -e " "', "ok"},
  646. {progname .. ' -e "os.exit(0, true)"', "ok"},
  647. {progname .. ' -e "os.exit(20, true)"', "exit", 20},
  648. }
  649. print("\n(some error messages are expected now)")
  650. for _, v in ipairs(tests) do
  651. local x, y, z = io.popen(v[1]):close()
  652. local x1, y1, z1 = os.execute(v[1])
  653. assert(x == x1 and y == y1 and z == z1)
  654. if v[2] == "ok" then
  655. assert(x and y == 'exit' and z == 0)
  656. else
  657. assert(not x and y == v[2]) -- correct status and 'what'
  658. -- correct code if known (but always different from 0)
  659. assert((v[3] == nil and z > 0) or v[3] == z)
  660. end
  661. end
  662. end
  663. -- testing tmpfile
  664. f = io.tmpfile()
  665. assert(io.type(f) == "file")
  666. f:write("alo")
  667. f:seek("set")
  668. assert(f:read"a" == "alo")
  669. end --}
  670. print'+'
  671. print("testing date/time")
  672. assert(os.date("") == "")
  673. assert(os.date("!") == "")
  674. assert(os.date("\0\0") == "\0\0")
  675. assert(os.date("!\0\0") == "\0\0")
  676. local x = string.rep("a", 10000)
  677. assert(os.date(x) == x)
  678. local t = os.time()
  679. D = os.date("*t", t)
  680. assert(os.date(string.rep("%d", 1000), t) ==
  681. string.rep(os.date("%d", t), 1000))
  682. assert(os.date(string.rep("%", 200)) == string.rep("%", 100))
  683. local function checkDateTable (t)
  684. _G.D = os.date("*t", t)
  685. assert(os.time(D) == t)
  686. load(os.date([[assert(D.year==%Y and D.month==%m and D.day==%d and
  687. D.hour==%H and D.min==%M and D.sec==%S and
  688. D.wday==%w+1 and D.yday==%j)]], t))()
  689. _G.D = nil
  690. end
  691. checkDateTable(os.time())
  692. if not _port then
  693. -- assume that time_t can represent these values
  694. checkDateTable(0)
  695. checkDateTable(1)
  696. checkDateTable(1000)
  697. checkDateTable(0x7fffffff)
  698. checkDateTable(0x80000000)
  699. end
  700. checkerr("invalid conversion specifier", os.date, "%")
  701. checkerr("invalid conversion specifier", os.date, "%9")
  702. checkerr("invalid conversion specifier", os.date, "%")
  703. checkerr("invalid conversion specifier", os.date, "%O")
  704. checkerr("invalid conversion specifier", os.date, "%E")
  705. checkerr("invalid conversion specifier", os.date, "%Ea")
  706. checkerr("not an integer", os.time, {year=1000, month=1, day=1, hour='x'})
  707. checkerr("not an integer", os.time, {year=1000, month=1, day=1, hour=1.5})
  708. checkerr("missing", os.time, {hour = 12}) -- missing date
  709. if string.packsize("i") == 4 then -- 4-byte ints
  710. checkerr("field 'year' is out-of-bound", os.time,
  711. {year = -(1 << 31) + 1899, month = 1, day = 1})
  712. checkerr("field 'year' is out-of-bound", os.time,
  713. {year = -(1 << 31), month = 1, day = 1})
  714. if math.maxinteger > 2^31 then -- larger lua_integer?
  715. checkerr("field 'year' is out-of-bound", os.time,
  716. {year = (1 << 31) + 1900, month = 1, day = 1})
  717. end
  718. end
  719. if not _port then
  720. -- test Posix-specific modifiers
  721. assert(type(os.date("%Ex")) == 'string')
  722. assert(type(os.date("%Oy")) == 'string')
  723. -- test large dates (assume at least 4-byte ints and time_t)
  724. local t0 = os.time{year = 1970, month = 1, day = 0}
  725. local t1 = os.time{year = 1970, month = 1, day = 0, sec = (1 << 31) - 1}
  726. assert(t1 - t0 == (1 << 31) - 1)
  727. t0 = os.time{year = 1970, month = 1, day = 1}
  728. t1 = os.time{year = 1970, month = 1, day = 1, sec = -(1 << 31)}
  729. assert(t1 - t0 == -(1 << 31))
  730. -- test out-of-range dates (at least for Unix)
  731. if maxint >= 2^62 then -- cannot do these tests in Small Lua
  732. -- no arith overflows
  733. checkerr("out-of-bound", os.time, {year = -maxint, month = 1, day = 1})
  734. if string.packsize("i") == 4 then -- 4-byte ints
  735. if testerr("out-of-bound", os.date, "%Y", 2^40) then
  736. -- time_t has 4 bytes and therefore cannot represent year 4000
  737. print(" 4-byte time_t")
  738. checkerr("cannot be represented", os.time, {year=4000, month=1, day=1})
  739. else
  740. -- time_t has 8 bytes; an int year cannot represent a huge time
  741. print(" 8-byte time_t")
  742. checkerr("cannot be represented", os.date, "%Y", 2^60)
  743. -- this is the maximum year
  744. assert(tonumber(os.time
  745. {year=(1 << 31) + 1899, month=12, day=31, hour=23, min=59, sec=59}))
  746. -- this is too much
  747. checkerr("represented", os.time,
  748. {year=(1 << 31) + 1899, month=12, day=31, hour=23, min=59, sec=60})
  749. end
  750. -- internal 'int' fields cannot hold these values
  751. checkerr("field 'day' is out-of-bound", os.time,
  752. {year = 0, month = 1, day = 2^32})
  753. checkerr("field 'month' is out-of-bound", os.time,
  754. {year = 0, month = -((1 << 31) + 1), day = 1})
  755. checkerr("field 'year' is out-of-bound", os.time,
  756. {year = (1 << 31) + 1900, month = 1, day = 1})
  757. else -- 8-byte ints
  758. -- assume time_t has 8 bytes too
  759. print(" 8-byte time_t")
  760. assert(tonumber(os.date("%Y", 2^60)))
  761. -- but still cannot represent a huge year
  762. checkerr("cannot be represented", os.time, {year=2^60, month=1, day=1})
  763. end
  764. end
  765. end
  766. do
  767. local D = os.date("*t")
  768. local t = os.time(D)
  769. if D.isdst == nil then
  770. print("no daylight saving information")
  771. else
  772. assert(type(D.isdst) == 'boolean')
  773. end
  774. D.isdst = nil
  775. local t1 = os.time(D)
  776. assert(t == t1) -- if isdst is absent uses correct default
  777. end
  778. local D = os.date("*t")
  779. t = os.time(D)
  780. D.year = D.year-1;
  781. local t1 = os.time(D)
  782. -- allow for leap years
  783. assert(math.abs(os.difftime(t,t1)/(24*3600) - 365) < 2)
  784. -- should not take more than 1 second to execute these two lines
  785. t = os.time()
  786. t1 = os.time(os.date("*t"))
  787. local diff = os.difftime(t1,t)
  788. assert(0 <= diff and diff <= 1)
  789. diff = os.difftime(t,t1)
  790. assert(-1 <= diff and diff <= 0)
  791. local t1 = os.time{year=2000, month=10, day=1, hour=23, min=12}
  792. local t2 = os.time{year=2000, month=10, day=1, hour=23, min=10, sec=19}
  793. assert(os.difftime(t1,t2) == 60*2-19)
  794. -- since 5.3.3, 'os.time' normalizes table fields
  795. t1 = {year = 2005, month = 1, day = 1, hour = 1, min = 0, sec = -3602}
  796. os.time(t1)
  797. assert(t1.day == 31 and t1.month == 12 and t1.year == 2004 and
  798. t1.hour == 23 and t1.min == 59 and t1.sec == 58 and
  799. t1.yday == 366)
  800. io.output(io.stdout)
  801. local t = os.date('%d %m %Y %H %M %S')
  802. local d, m, a, h, min, s = string.match(t,
  803. "(%d+) (%d+) (%d+) (%d+) (%d+) (%d+)")
  804. d = tonumber(d)
  805. m = tonumber(m)
  806. a = tonumber(a)
  807. h = tonumber(h)
  808. min = tonumber(min)
  809. s = tonumber(s)
  810. io.write(string.format('test done on %2.2d/%2.2d/%d', d, m, a))
  811. io.write(string.format(', at %2.2d:%2.2d:%2.2d\n', h, min, s))
  812. io.write(string.format('%s\n', _VERSION))