Skip to content

Commit

Permalink
feat(nio/tests): with async context function (#374)
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 18, 2024
1 parent bbed61d commit a13a960
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions lua/nio/tests.lua
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,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 @@ -29,6 +31,7 @@ local with_timeout = function(func, timeout)
elseif not success then
error(string.format("Test task failed with message:\n%s", err))
end
return unpack(results)
end
end

Expand Down Expand Up @@ -56,4 +59,19 @@ local mt = {

setmetatable(nio.tests, mt)

---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(unpack(args))
end
local result = with_timeout(thunk, tonumber(vim.env.PLENARY_TEST_TIMEOUT))()
return result
end

return nio.tests

0 comments on commit a13a960

Please sign in to comment.