diff options
Diffstat (limited to 'tests/finalizer.lua')
-rw-r--r-- | tests/finalizer.lua | 81 |
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 | |||
11 | require "lanes" | ||
12 | |||
13 | local FN= "finalizer-test.tmp" | ||
14 | |||
15 | local cleanup | ||
16 | |||
17 | local which= os.time() % 2 -- 0/1 | ||
18 | |||
19 | local 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 | ||
37 | end | ||
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 | -- | ||
43 | cleanup= 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" ) | ||
61 | end | ||
62 | |||
63 | local lgen = lanes.gen("*", lane) | ||
64 | |||
65 | io.stderr:write "Launching the lane!\n" | ||
66 | |||
67 | local h= lgen() | ||
68 | |||
69 | local _,err,stack= h:join() -- wait for the lane (no automatic error propagation) | ||
70 | if 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" ) | ||
74 | end | ||
75 | |||
76 | local f= io.open(FN,"r") | ||
77 | if f then | ||
78 | error( "CLEANUP DID NOT WORK: "..FN.." still exists!" ) | ||
79 | end | ||
80 | |||
81 | io.stderr:write "Finished!\n" | ||