aboutsummaryrefslogtreecommitdiff
path: root/tests/finalizer.lua
diff options
context:
space:
mode:
Diffstat (limited to 'tests/finalizer.lua')
-rw-r--r--tests/finalizer.lua81
1 files changed, 81 insertions, 0 deletions
diff --git a/tests/finalizer.lua b/tests/finalizer.lua
new file mode 100644
index 0000000..c94b36d
--- /dev/null
+++ b/tests/finalizer.lua
@@ -0,0 +1,81 @@
1--
2-- Test resource cleanup
3--
4-- This feature was ... by discussion on the Lua list about exceptions.
5-- The idea is to always run a certain block at exit, whether due to success
6-- or error. Normally, 'pcall' would be used for such but as Lua already
7-- does that, simply giving a 'cleanup=function' parameter is a logical
8-- thing to do. -- AKa 22-Jan-2009
9--
10
11require "lanes"
12
13local FN= "finalizer-test.tmp"
14
15local cleanup
16
17local which= os.time() % 2 -- 0/1
18
19local function lane()
20
21 set_finalizer(cleanup)
22
23 local f,err= io.open(FN,"w")
24 if not f then
25 error( "Could not create "..FN..": "..err )
26 end
27
28 f:write( "Test file that should get removed." )
29
30 io.stderr:write( "File "..FN.." created\n" )
31
32 if which==0 then
33 error("aa") -- exception here; the value needs NOT be a string
34 end
35
36 -- no exception
37end
38
39--
40-- This is called at the end of the lane; whether succesful or not.
41-- Gets the 'error()' parameter as parameter ('nil' if normal return).
42--
43cleanup= function(err)
44
45 -- An error in finalizer will override an error (or success) in the main
46 -- chunk.
47 --
48 --error( "This is important!" )
49
50 if err then
51 io.stderr:write( "Cleanup after error: "..tostring(err).."\n" )
52 else
53 io.stderr:write( "Cleanup after normal return\n" )
54 end
55
56 local _,err2= os.remove(FN)
57 assert(not err2) -- if this fails, it will be shown in the calling script
58 -- as an error from the lane itself
59
60 io.stderr:write( "Removed file "..FN.."\n" )
61end
62
63local lgen = lanes.gen("*", lane)
64
65io.stderr:write "Launching the lane!\n"
66
67local h= lgen()
68
69local _,err,stack= h:join() -- wait for the lane (no automatic error propagation)
70if err then
71 assert(stack)
72 io.stderr:write( "Lane error: "..tostring(err).."\n" )
73 io.stderr:write( "\t", table.concat(stack,"\t\n"), "\n" )
74end
75
76local f= io.open(FN,"r")
77if f then
78 error( "CLEANUP DID NOT WORK: "..FN.." still exists!" )
79end
80
81io.stderr:write "Finished!\n"