lune/tests/task/wait.luau

79 lines
1.9 KiB
Text
Raw Permalink Normal View History

local process = require("@lune/process")
local stdio = require("@lune/stdio")
2023-06-08 10:21:00 +01:00
local task = require("@lune/task")
2023-09-16 21:03:01 +01:00
-- NOTE: For now we don't test accuracy of waiting, the only thing
-- we guarantee is that task.wait waits for _at least_ the amount
-- of time given. Windows sleep is extremely inaccurate.
local TEST_ACCURACY = false
2023-09-16 21:03:01 +01:00
local EPSILON = if process.os == "windows" then 12 / 1_000 else 8 / 1_000
2023-01-21 18:33:33 +00:00
2023-01-22 19:44:23 +00:00
local function test(expected: number)
2023-01-21 18:33:33 +00:00
local start = os.clock()
local returned = task.wait(expected)
if typeof(returned) ~= "number" then
error(
string.format(
"Expected task.wait to return a number, got %s %s",
typeof(returned),
stdio.format(returned)
),
2
)
end
2023-09-16 21:03:01 +01:00
local elapsed = os.clock() - start
if elapsed < expected then
error(
string.format(
"Expected task.wait to yield for at least %.3f seconds, yielded for %.3f seconds",
expected,
elapsed
)
)
end
if not TEST_ACCURACY then
return
end
local difference = math.abs(elapsed - expected)
2023-01-21 18:33:33 +00:00
if difference > EPSILON then
error(
string.format(
"Elapsed time diverged too much from argument!"
.. "\nGot argument of %.3fms and elapsed time of %.3fms"
.. "\nGot maximum difference of %.3fms and real difference of %.3fms",
expected * 1_000,
elapsed * 1_000,
EPSILON * 1_000,
difference * 1_000
2023-01-21 18:33:33 +00:00
)
)
end
end
2023-01-22 19:44:23 +00:00
local function measure(duration: number)
2023-01-21 18:33:33 +00:00
for _ = 1, 5 do
test(duration)
end
end
2023-08-21 03:54:45 +01:00
-- About 20ms is the shortest safe sleep time on Windows, but
-- Linux and macOS can do down to about 10ms or less safely
measure(if process.os == "windows" then 15 / 1_000 else 5 / 1_000)
2023-01-21 18:33:33 +00:00
measure(1 / 60)
measure(1 / 30)
measure(1 / 20)
measure(1 / 10)
2023-01-22 19:44:23 +00:00
-- Wait should work in other threads
2023-01-22 19:44:23 +00:00
local flag: boolean = false
2023-01-23 04:00:09 +00:00
task.spawn(function()
2023-01-23 00:25:36 +00:00
task.wait(0.1)
2023-01-23 07:38:32 +00:00
flag = true
2023-01-23 04:00:09 +00:00
end)
2023-01-23 22:39:16 +00:00
assert(not flag, "Wait failed while inside task-spawned thread (1)")
2023-01-23 00:25:36 +00:00
task.wait(0.2)
2023-01-23 22:39:16 +00:00
assert(flag, "Wait failed while inside task-spawned thread (2)")