|
| 1 | +local assertresume = require('libs.coroutine').assertresume |
| 2 | + |
| 3 | +describe('ext_coro.assertresume', function() |
| 4 | + _G.unpack = table.unpack |
| 5 | + |
| 6 | + test('resumes and returns correctly', function() |
| 7 | + local co = coroutine.create(function(...) |
| 8 | + return ... |
| 9 | + end) |
| 10 | + |
| 11 | + local args = {1, 2, false} |
| 12 | + local rtn_args |
| 13 | + assert.no_error(function() |
| 14 | + rtn_args = {assertresume(co, table.unpack(args))} |
| 15 | + end) |
| 16 | + assert.same(args, rtn_args) |
| 17 | + end) |
| 18 | + |
| 19 | + test('throws an error', function() |
| 20 | + -- note: we are not checking for the error message |
| 21 | + -- since assertresume's error message will |
| 22 | + -- depend on the actual stack traceback |
| 23 | + local co = coroutine.create(error) |
| 24 | + assert.has_error(function() |
| 25 | + assertresume(co, 'test!') |
| 26 | + end) |
| 27 | + end) |
| 28 | + |
| 29 | + test('throws an error with the correct stack', function() |
| 30 | + local function a() |
| 31 | + error('test!') |
| 32 | + end |
| 33 | + local function b() |
| 34 | + a() |
| 35 | + end |
| 36 | + local function f() |
| 37 | + b() |
| 38 | + end |
| 39 | + |
| 40 | + -- normally resume the coroutine to get its expected stack traceback |
| 41 | + local co = coroutine.create(f) |
| 42 | + coroutine.resume(co) |
| 43 | + local expected_traceback = debug.traceback(co) |
| 44 | + |
| 45 | + -- re-create the coroutine but resume it with assertresume this time |
| 46 | + -- and see if we get a matching stack traceback to expected_traceback |
| 47 | + -- |
| 48 | + -- note bellow "traceback" is technically the error message |
| 49 | + -- though since assertresume passes the traceback as the message |
| 50 | + -- we have to it this way since we can't just debug.traceback it |
| 51 | + co = coroutine.create(f) |
| 52 | + local success, traceback = pcall(assertresume, co) |
| 53 | + assert.falsy(success) -- just in case |
| 54 | + |
| 55 | + -- truncate the amount of characters we will be matching against |
| 56 | + -- without the error message |
| 57 | + traceback = traceback:gsub('^.-(stack traceback.+)', '%1'):sub(1, #expected_traceback) |
| 58 | + |
| 59 | + assert.equal(expected_traceback, traceback) |
| 60 | + end) |
| 61 | +end) |
0 commit comments