|
| 1 | +local Job = require "plenary.job" |
| 2 | + |
| 3 | +local Timing = {} |
| 4 | + |
| 5 | +function Timing:log(name) |
| 6 | + self[name] = vim.loop.uptime() |
| 7 | +end |
| 8 | + |
| 9 | +function Timing:check(from, to, min_elapsed) |
| 10 | + assert(self[from], "did not log " .. from) |
| 11 | + assert(self[to], "did not log " .. to) |
| 12 | + local elapsed = self[to] - self[from] |
| 13 | + assert(min_elapsed <= elapsed, string.format("only took %s to get from %s to %s - expected at least %s", elapsed, from, to, min_elapsed)) |
| 14 | +end |
| 15 | + |
| 16 | +describe("Async test", function() |
| 17 | + it("can resume testing with vim.defer_fn", function() |
| 18 | + local co = coroutine.running() |
| 19 | + assert(co, "not running inside a coroutine") |
| 20 | + |
| 21 | + local timing = setmetatable({}, {__index = Timing}) |
| 22 | + |
| 23 | + vim.defer_fn(function() |
| 24 | + coroutine.resume(co) |
| 25 | + end, 200) |
| 26 | + timing:log("before") |
| 27 | + coroutine.yield() |
| 28 | + timing:log("after") |
| 29 | + timing:check("before", "after", 0.1) |
| 30 | + end) |
| 31 | + |
| 32 | + it("can resume testing from job callback", function() |
| 33 | + local co = coroutine.running() |
| 34 | + assert(co, "not running inside a coroutine") |
| 35 | + |
| 36 | + local timing = setmetatable({}, {__index = Timing}) |
| 37 | + |
| 38 | + Job:new { |
| 39 | + command = "bash", |
| 40 | + args = { "-ce", [[ |
| 41 | + sleep 0.2 |
| 42 | + echo hello |
| 43 | + sleep 0.2 |
| 44 | + echo world |
| 45 | + sleep 0.2 |
| 46 | + exit 42 |
| 47 | + ]] }, |
| 48 | + on_stdout = function(_, data) |
| 49 | + timing:log(data) |
| 50 | + end, |
| 51 | + on_exit = function(_, exit_status) |
| 52 | + timing:log("exit") |
| 53 | + --This is required so that the rest of the test will run in a proper context |
| 54 | + vim.schedule(function() |
| 55 | + coroutine.resume(co, exit_status) |
| 56 | + end) |
| 57 | + end |
| 58 | + }:start() |
| 59 | + timing:log("job started") |
| 60 | + local exit_status = coroutine.yield() |
| 61 | + timing:log("job finished") |
| 62 | + assert.are.equal(exit_status, 42) |
| 63 | + |
| 64 | + timing:check("job started", "job finished", 0.3) |
| 65 | + timing:check("job started", "hello", 0.1) |
| 66 | + timing:check("hello", "world", 0.1) |
| 67 | + timing:check("world", "job finished", 0.1) |
| 68 | + end) |
| 69 | +end) |
0 commit comments