Skip to content

Commit

Permalink
Add async context function to tests module
Browse files Browse the repository at this point in the history
As a user of the nio library when writing tests I might want to run an
asynchronous function within a synchronous function and wait for the
result.  This function acts as a synchronous wrapper around the
asynchronous function.
  • Loading branch information
HiPhish committed Mar 1, 2024
1 parent 4440cc2 commit e8bfae9
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions lua/nio/tests.lua
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@ local nio = {}
nio.tests = {}

local with_timeout = function(func, timeout)
local success, err
local success, err, results
return function()
local task = tasks.run(func, function(success_, err_)
local task = tasks.run(func, function(success_, ...)
success = success_
if not success_ then
err = err_
err = ...
else
results = {...}
end
end)

Expand All @@ -26,6 +28,7 @@ local with_timeout = function(func, timeout)
elseif not success then
error(string.format("Test task failed with message:\n%s", err))
end
return table.unpack(results)
end
end

Expand All @@ -45,4 +48,20 @@ nio.tests.after_each = function(async_func)
after_each(with_timeout(async_func))
end

---Run the given function, applied to the remaining arguments, in an
---asynchronous context. The return value (or values) is the return value of
---the asynchronous function.
---@param async_func function Function to execute
---@param ... any Arguments to `async_func`
---@return any ... Return values of `async_func`
nio.tests.with_async_context = function(async_func, ...)
local args = {...}
local thunk = function()
return async_func(table.unpack(args))
end
local result = with_timeout(thunk, tonumber(vim.env.PLENARY_TEST_TIMEOUT))()
return result
end


return nio.tests

0 comments on commit e8bfae9

Please sign in to comment.