tarantool / luatest

Tarantool test framework written in Lua
https://www.tarantool.io/en/doc/latest/reference/reference_rock/luatest/luatest_overview/
Other
40 stars 11 forks source link

Extend hooks API #181

Open yngvar-antonsson opened 3 years ago

yngvar-antonsson commented 3 years ago

It would be nice to write one-line hooks like

g.after_test('test_smth', function()
    g.master.net_box:eval([[
        -- do something
    ]])
end)

in such way:

g.after_test('test_smth', g.master.net_box:eval, [[ -- do something ]])
rosik commented 3 years ago

It may be a good idea. In other words, we need to save not only the function itself but its arguments too.

But it may be challenging. Suppose I want to create a closure, like this:

function closure(fn, ...)
    return function()
        return fn(...)
    end
end

fn = closure(math.sqrt, 4) -- returns a function which can be called without arguments
fn() -- returns 2

But Lua doesn't allow to do so:

closure.lua:3: cannot use '...' outside a vararg function near '...'

The solution is the following:

function closure(fn, ...)
    local args = {n = select('#', ...), ...}
    return function()
        return fn(unpack(args, 1, args.n))
    end
end

fn1 = closure(print, 'a', 'b', 'c')
fn2 = closure(print, 3, 4, nil)

fn1() -- prints "a b c"
fn2() -- prints "3 4 nil"

Look, it doesn't even lose a nil.