aboutsummaryrefslogtreecommitdiff
path: root/tests/finalizer.lua
blob: dc9ed34e5b24e017520e0defe2d468c96b03f094 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
--
-- Test resource cleanup
--
-- This feature was ... by discussion on the Lua list about exceptions.
-- The idea is to always run a certain block at exit, whether due to success
-- or error. Normally, 'pcall' would be used for such but as Lua already
-- does that, simply giving a 'cleanup=function' parameter is a logical
-- thing to do.     -- AKa 22-Jan-2009
--

local lanes = require "lanes"
lanes.configure()

local FN= "finalizer-test.tmp"

local cleanup

local which= os.time() % 2  -- 0/1

local function lane()

    set_finalizer(cleanup)

    local f,err= io.open(FN,"w")
    if not f then
        error( "Could not create "..FN..": "..err )
    end

    f:write( "Test file that should get removed." )

    io.stderr:write( "File "..FN.." created\n" )    

    if which==0 then
        print "you loose"
        error("aa")    -- exception here; the value needs NOT be a string
    end

    -- no exception
end

-- 
-- This is called at the end of the lane; whether succesful or not.
-- Gets the 'error()' parameter as parameter ('nil' if normal return).
--
cleanup= function(err)

    -- An error in finalizer will override an error (or success) in the main
    -- chunk.
    --
    --error( "This is important!" )

    if err then
        io.stderr:write( "Cleanup after error: "..tostring(err).."\n" )
    else
        io.stderr:write( "Cleanup after normal return\n" )
    end
        
    local _,err2= os.remove(FN)
    print( "file removal result: ", tostring( err2))
    assert(not err2)    -- if this fails, it will be shown in the calling script
                        -- as an error from the lane itself
    
    io.stderr:write( "Removed file "..FN.."\n" )
end

local lgen = lanes.gen("*", lane)

io.stderr:write "Launching the lane!\n"

local h= lgen()

local _,err,stack= h:join()   -- wait for the lane (no automatic error propagation)
if err then
    assert(stack)
    io.stderr:write( "Lane error: "..tostring(err).."\n" )
    io.stderr:write( "\t", table.concat(stack,"\t\n"), "\n" )
end

local f= io.open(FN,"r")
if f then
    error( "CLEANUP DID NOT WORK: "..FN.." still exists!" )
end

io.stderr:write "Finished!\n"